-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdebounce.ts
58 lines (55 loc) · 1.38 KB
/
debounce.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Please refer to the terms of the license agreement in the root of the project
*
* (c) 2024 Feedzai
*/
export type DebounceFunction<TArgs extends any[]> = {
(...args: TArgs): void;
/**
* Cancels the debounced function
*/
cancel(): void;
/**
* Checks if there is any invocation debounced
*/
isPending(): boolean;
/**
* Runs the debounced function immediately
*/
flush(...args: TArgs): void;
};
/**
* Given a delay and a function returns a new function
* that will only call the source function after delay
* milliseconds have passed without any invocations.
*
* The debounce function comes with a `cancel` method
* to cancel delayed `func` invocations and a `flush`
* method to invoke them immediately
*/
export function debounce<TArgs extends any[]>(
{ delay }: { delay: number },
func: (...args: TArgs) => any
) {
let timer: NodeJS.Timeout | undefined = undefined;
let active = true;
const debounced: DebounceFunction<TArgs> = (...args: TArgs) => {
if (active) {
clearTimeout(timer);
timer = setTimeout(() => {
active && func(...args);
timer = undefined;
}, delay);
} else {
func(...args);
}
};
debounced.isPending = () => {
return timer !== undefined;
};
debounced.cancel = () => {
active = false;
};
debounced.flush = (...args: TArgs) => func(...args);
return debounced;
}