-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathDebouncing.js
61 lines (51 loc) · 1.12 KB
/
Debouncing.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
53
54
55
56
57
58
59
60
61
function findMax(array) {
if (array.length === 0) {
return null;
}
return Math.max.apply(null, array);
}
var input = [1, 2, 3, 4, 5];
console.log(findMax(input));
function debouncing(callback, wait) {
var timestamp = Date.now(),
timeOut;
var call = function () {
if (Date.now() - timestamp < wait) {
if (timeOut) {
clearTimeOut(timeOut);
}
timeOut = setTimeOut(call, wait - ((Date.now() - timestamp));
} else {
timestamp = Date.now();
callback.apply(this);
}
};
return call;
}
var wait = 1000;
var debouncedFn = debouncing(callback, wait);
...
debounceFn(); // queues a setTimeout .
debounceFn(); // queues a setTimeout .
debounceFn(); // queues a setTimeout .
debounceFn();
debounceFn();
...wait 1000...
-> this is where callback() should occur
function debouncing(callback, wait) {
var timeout;
function call () {
callback();
return;
}
return function () {
clearTimeout(timeout);
timeout = setTimeout(call, wait);
};
}
function log() {
console.log("meow");
}
logDebounced = debouncing(log, 1000);
logDebounced();
logDebounced();