-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeferred.ts
61 lines (54 loc) · 1.52 KB
/
deferred.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
59
60
61
type Deferred<TArgs extends readonly unknown[]> = {
(...args: TArgs): void;
/**
* If a call to the wrapped callback is scheduled, cancel it. Has no effect
* if no call is scheduled.
*/
cancel(): void;
/**
* If a call to the wrapped callback is scheduled, call it immediately
* instead of waiting for the timeout to elapse. Has no effect if no call is
* scheduled.
*/
flush(): void;
};
/**
* Wrap a callback so that it is not called until at least `timeout`
* milliseconds have elapsed since the previous call to the wrapper. **If the
* deferred wrapper is always called before the timeout expires, the wrapped
* function may never be called!**
*/
const createDeferred = <TArgs extends readonly unknown[] = readonly []>(
timeout: number,
callback: (...args: TArgs) => void,
): Deferred<TArgs> => {
let scheduled: { readonly args: TArgs; readonly handle: any } | undefined;
const deferred = (...newArgs: TArgs): void => {
if (scheduled) {
clearTimeout(scheduled.handle);
}
scheduled = {
args: newArgs,
handle: setTimeout(() => {
scheduled = undefined;
callback(...newArgs);
}, timeout),
};
};
deferred.cancel = () => {
if (scheduled) {
clearTimeout(scheduled.handle);
scheduled = undefined;
}
};
deferred.flush = () => {
if (scheduled) {
clearTimeout(scheduled.handle);
const { args } = scheduled;
scheduled = undefined;
callback(...args);
}
};
return deferred;
};
export { createDeferred };