-
Notifications
You must be signed in to change notification settings - Fork 2
/
Function.ts
40 lines (31 loc) · 858 Bytes
/
Function.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
type Callback = (...args: unknown[]) => void;
export function debounce(cb: Callback, delay: number, leading = true): Callback
{
let timeout: NodeJS.Timeout | undefined;
return (...args) => {
clearTimeout(timeout);
leading && !timeout && cb(...args);
timeout = setTimeout(() => {
!leading && cb(...args);
timeout = undefined;
}, delay);
};
}
export function throttle (cb: Callback, limit: number): Callback
{
let last: number, timeout: NodeJS.Timeout;
return (...args) => {
const now = Date.now();
if (!last) { cb(...args); last = now; }
else {
clearTimeout(timeout);
const delay = limit - (now - last);
timeout = setTimeout(() => {
const delay = Date.now() - last;
if (delay < limit) return;
last = Date.now();
cb(...args);
}, delay);
}
};
}