-
Notifications
You must be signed in to change notification settings - Fork 0
/
debounced.ts
30 lines (30 loc) · 831 Bytes
/
debounced.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
export default <T extends (...args: any[]) => void>(
fn: T,
delayMs: number,
maxDelayMs: number = Infinity
): {
cancel: () => void;
function: T;
} => {
let lastId: ReturnType<typeof setTimeout> | undefined = undefined;
let sequenceStarted: number | undefined = undefined;
return {
cancel: () => clearTimeout(lastId as any),
function: function (this: any) {
const now = Date.now();
const cb = () => {
fn.apply(this, arguments as any);
sequenceStarted = undefined;
};
clearTimeout(lastId as any);
if (sequenceStarted == undefined) {
sequenceStarted = now;
lastId = setTimeout(cb, delayMs);
} else if (now - sequenceStarted <= maxDelayMs) {
lastId = setTimeout(cb, delayMs);
} else {
cb();
}
} as any,
};
};