-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
debounce.js
52 lines (47 loc) · 1.33 KB
/
debounce.js
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
/**
* Debounce function, includes leading and trailing options (lodash-like)
* @param {Function} func - function to be debounced
* @param {Number} delay - delay in milliseconds
* @param {Object} options - options object
* @param {Boolean} options.leading - whether to invoke the function on the leading edge
* @param {Boolean} options.trailing - whether to invoke the function on the trailing edge
* @returns {Function} - debounced function
*/
export function debounce(func, delay, options = {}) {
let timeoutId;
let lastArgs;
let lastThis;
let calledOnce = false;
const { leading = false, trailing = true } = options;
function invokeFunc() {
func.apply(lastThis, lastArgs);
lastArgs = null;
lastThis = null;
}
return function (...args) {
lastArgs = args;
lastThis = this;
if (!timeoutId) {
if (leading && !calledOnce) {
invokeFunc();
calledOnce = true;
}
timeoutId = setTimeout(() => {
if (!trailing) {
clearTimeout(timeoutId);
timeoutId = null;
} else {
invokeFunc();
timeoutId = null;
}
calledOnce = false;
}, delay);
} else if (trailing) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
invokeFunc();
timeoutId = null;
}, delay);
}
};
}