-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
68 lines (62 loc) · 1.86 KB
/
index.js
File metadata and controls
68 lines (62 loc) · 1.86 KB
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
/**
* Returns a debounced function that will delay the execution of `func` until
* after `wait` milliseconds have passed since the last time the debounced
* function was called. If `func` is called again before `wait` milliseconds,
* the timer is reset and the new call's execution is delayed again.
*
* @param {function} func - The function to be debounced.
* @param {number} [wait=500] - The number of milliseconds to delay the execution
* of `func`.
* @return {function} - The debounced function.
*/
export const debouncing = (func, wait = 500) => {
let timeout;
let argsRef = null;
let contextRef = null;
function execute(...args) {
contextRef = this;
argsRef = args;
const semaphore = () => {
clear();
executeFunc(contextRef);
};
clear();
timeout = setTimeout(semaphore, wait);
}
/**
* Cancels the pending execution of `func` and resets the timer.
*/
const clear = () => {
clearTimeout(timeout);
timeout = null;
};
/**
* Applies the original function `func` with the cached context and arguments.
* @param {Object} contextRef - The context of the function call.
* @private
*/
const executeFunc = (contextRefPassed) => {
const runFunc = func.apply(contextRefPassed, argsRef);
argsRef = null;
contextRef = null;
return runFunc;
};
/**
* Cancels the delayed execution of `func`.
*/
execute.cancel = () => clear();
/**
* Cancels the pending execution of `func` and executes it immediately.
* @return {*} - The return value of `func`.
*/
execute.cancelAndExecute = () => {
execute.cancel();
if (argsRef) return executeFunc(contextRef);
};
/**
* Checks if there's a pending debounced execution.
* @return {boolean} - `true` if the debounced function is waiting to execute.
*/
execute.pending = () => timeout !== null;
return execute;
};