debounce.ts 1.35 KB
Newer Older
1
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
Hanwen Cheng's avatar
Hanwen Cheng committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// This file is part of Parity.

// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Parity.  If not, see <http://www.gnu.org/licenses/>.

Thibaut Sardan's avatar
Thibaut Sardan committed
17
/**
18
19
 * Creates and returns a new debounced version of the passed function that will
 * postpone its execution until after wait milliseconds have elapsed since
Thibaut Sardan's avatar
Thibaut Sardan committed
20
21
22
23
24
 * the last time it was invoked.
 *
 * @type  {T}                item    type
 * @param {(any) => any}     function to debounce
 * @param {number}           time in milliseconds
25
 *
Thibaut Sardan's avatar
Thibaut Sardan committed
26
 *
27
 * @return {any[]}            the debounced function
Thibaut Sardan's avatar
Thibaut Sardan committed
28
 */
29
let timeout: any;
Thibaut Sardan's avatar
Thibaut Sardan committed
30

31
export function debounce(fn: any, time: number): () => void {
32
	return function debouncedFunction(...args: any[]): void {
33
		const functionCall = (): any => fn.apply(null, ...args);
Thibaut Sardan's avatar
Thibaut Sardan committed
34

35
36
37
38
		clearTimeout(timeout);
		timeout = setTimeout(functionCall, time);
	};
}