-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdebounce.js
More file actions
40 lines (34 loc) · 921 Bytes
/
Copy pathdebounce.js
File metadata and controls
40 lines (34 loc) · 921 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
/**
* Debounce Description:
* Creates and returns a new debounced version of the passed function
* which will postpone its execution until after wait milliseconds
* have elapsed since the last time it was invoked.
**/
// Implementation
function debounce (fn, wait) {
let debounced = false;
return function () {
var args = arguments;
if (debounced) {
clearTimeout(debounced)
}
debounced = setTimeout(function() {
console.log(args, fn);
fn.apply(this, args);
debounced = false;
}, wait);
};
}
// Example usage
function sayHello (name, age) {
// console.log(this);
console.log('hello ' + name + age)
}
var sayHelloDebounced = debounce(sayHello, 500)
// Initial test - expect sayHello to only be called once
sayHelloDebounced('alice', 1)
// debounced = false
sayHelloDebounced('bob', 2)
setTimeout(function() { sayHelloDebounced('charlie', 3) }, 200)