forked from triggerdotdev/trigger.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththrottle.ts
More file actions
28 lines (24 loc) · 665 Bytes
/
throttle.ts
File metadata and controls
28 lines (24 loc) · 665 Bytes
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
/** A throttle that fires the first call immediately and ensures the last call during the duration is also fired. */
export function throttle(
func: (...args: any[]) => void,
durationMs: number
): (...args: any[]) => void {
let timeoutId: NodeJS.Timeout | null = null;
let nextArgs: any[] | null = null;
const wrapped = (...args: any[]) => {
if (timeoutId) {
nextArgs = args;
return;
}
func(...args);
timeoutId = setTimeout(() => {
timeoutId = null;
if (nextArgs) {
const argsToUse = nextArgs;
nextArgs = null;
wrapped(...argsToUse);
}
}, durationMs);
};
return wrapped;
}