-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathindex.ts
88 lines (72 loc) · 2.4 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import {type DependencyList, useEffect, useMemo, useRef} from 'react';
import {useUnmountEffect} from '../useUnmountEffect/index.js';
export type DebouncedFunction<Fn extends (...args: any[]) => any> = (
this: ThisParameterType<Fn>,
...args: Parameters<Fn>
) => void;
/**
* Makes passed function debounced, otherwise acts like `useCallback`.
*
* @param callback Function that will be debounced.
* @param deps Dependencies list when to update callback. It also replaces invoked
* callback for scheduled debounced invocations.
* @param delay Debounce delay.
* @param maxWait The maximum time `callback` is allowed to be delayed before
* it's invoked. 0 means no max wait.
*/
export function useDebouncedCallback<Fn extends (...args: any[]) => any>(
callback: Fn,
deps: DependencyList,
delay: number,
maxWait = 0,
): DebouncedFunction<Fn> {
const timeout = useRef<ReturnType<typeof setTimeout>>();
const waitTimeout = useRef<ReturnType<typeof setTimeout>>();
const cb = useRef(callback);
const lastCall = useRef<{args: Parameters<Fn>; this: ThisParameterType<Fn>}>();
const clear = () => {
if (timeout.current) {
clearTimeout(timeout.current);
timeout.current = undefined;
}
if (waitTimeout.current) {
clearTimeout(waitTimeout.current);
waitTimeout.current = undefined;
}
};
// Cancel scheduled execution on unmount
useUnmountEffect(clear);
useEffect(() => {
cb.current = callback;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
return useMemo(() => {
const execute = () => {
clear();
if (!lastCall.current) {
return;
}
const context = lastCall.current;
lastCall.current = undefined;
cb.current.apply(context.this, context.args);
};
const wrapped = function (this, ...args) {
if (timeout.current) {
clearTimeout(timeout.current);
}
lastCall.current = {args, this: this};
// Plan regular execution
timeout.current = setTimeout(execute, delay);
// Plan maxWait execution if required
if (maxWait > 0 && !waitTimeout.current) {
waitTimeout.current = setTimeout(execute, maxWait);
}
} as DebouncedFunction<Fn>;
Object.defineProperties(wrapped, {
length: {value: callback.length},
name: {value: `${callback.name || 'anonymous'}__debounced__${delay}`},
});
return wrapped;
// eslint-disable-next-line react-hooks/exhaustive-deps,@typescript-eslint/no-unsafe-assignment
}, [delay, maxWait, ...deps]);
}