-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.ts
37 lines (35 loc) · 971 Bytes
/
utils.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
/**
* Promisify setTimeout
* @param millis the millis to sleep
*/
export const sleep = (millis: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, millis));
/**
* Function debouncer
*/
type DF = (this: ThisParameterType<void>, ...args: any[]) => void;
export const debounce = (func: DF, delay: number): DF => {
let timeout: NodeJS.Timeout;
return function (this: ThisParameterType<void>, ...args: any[]): void {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, delay);
};
};
/**
* Function throttler
*/
export const throttle = <T extends (...args: unknown[]) => ReturnType<T>>(
func: T,
delay: number
): ((this: ThisParameterType<T>, ...args: Parameters<T>) => void) => {
let last = 0;
return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
const now = Date.now();
if (now - last >= delay) {
func.apply(this, args);
last = now;
}
};
};