-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdebounce.js
More file actions
48 lines (36 loc) · 905 Bytes
/
debounce.js
File metadata and controls
48 lines (36 loc) · 905 Bytes
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
// https://davidwalsh.name/javascript-debounce-function
/**
* @function debounce
* Debounce a function call
*
* @param {Function} fnc Function to call when debounced
* @param {Number} wait Time to wait before calling <func>
* @param {Boolean} immediate Call <func> immediately?
*
* @example
* ```js
* let caller = debounce(() => {
* console.log("Debounced");
* }, 1000);
*
* caller();
* setTimeout(caller, 500);
* ```
*/
function debounce(func, wait, immediate = false) {
let timeout = null;
return function (...args) {
let later = () => {
timeout = null;
if (!immediate) {
func.apply(this, args);
}
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (immediate && !timeout) {
func.apply(this, args);
}
};
}
module.exports = debounce;