-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync.ts
44 lines (38 loc) · 955 Bytes
/
async.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
export function debounce<T extends Array<unknown>>(
fn: (...args: T) => void,
interval = 250,
immediate = true,
) {
let timeout: number | null = null;
return (...args: T) => {
timeout && clearTimeout(timeout);
timeout = setTimeout(() => {
if (!immediate) fn(...args);
}, interval);
if (immediate && !timeout) fn(...args);
};
}
export function throttle<T extends Array<unknown>>(
fn: (...args: T) => void,
interval = 250,
) {
let isThrottling = false;
return (...args: T) => {
if (!isThrottling) {
fn(...args);
isThrottling = true;
setTimeout(() => {
isThrottling = false;
}, interval);
}
};
}
export function wait(time = 1) {
return new Promise((resolve) => setTimeout(resolve, time));
}
export function timeout<R, T extends unknown[]>(
fn: (...args: T) => Promise<R>,
timeout = 250,
) {
return (...args: T) => Promise.race([fn(...args), wait(timeout)]);
}