-
Notifications
You must be signed in to change notification settings - Fork 1
/
throttled.ts
39 lines (37 loc) · 977 Bytes
/
throttled.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
/**
* Please refer to the terms of the license agreement in the root of the project
*
* (c) 2024 Feedzai
*/
export type ThrottledFunction<TArgs extends any[]> = {
(...args: TArgs): void;
/**
* Checks if there is any invocation throttled
*/
isThrottled(): boolean;
};
/**
* Given an interval and a function returns a new function
* that will only call the source function if interval milliseconds
* have passed since the last invocation
*/
export function throttle<TArgs extends any[]>(
{ interval }: { interval: number },
func: (...args: TArgs) => any
) {
let ready = true;
let timer: NodeJS.Timeout | undefined = undefined;
const throttled: ThrottledFunction<TArgs> = (...args: TArgs) => {
if (!ready) return;
func(...args);
ready = false;
timer = setTimeout(() => {
ready = true;
timer = undefined;
}, interval);
};
throttled.isThrottled = () => {
return timer !== undefined;
};
return throttled;
}