-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdebounce.js
42 lines (34 loc) · 902 Bytes
/
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
import curry from './curry';
import _enforceFunction from './internal/_enforceFunction';
import _enforceInterval from './internal/_enforceInterval';
function debounce(interval, operation) {
_enforceInterval(interval);
_enforceFunction(operation);
let lastArgs;
let lastResult;
let timer = null;
function cancel() {
clearTimeout(timer);
timer = null;
}
function runner() {
cancel();
lastResult = operation(...lastArgs);
}
function debounced(...args) {
lastArgs = args;
cancel();
timer = setTimeout(runner, interval);
return lastResult;
}
debounced.cancel = cancel;
return debounced;
}
/**
* `operation` is called `interval` milliseconds after the most recent call.
*
* @param {number} interval of milliseconds
* @param {Function} operation
* @return {any} the most recent result of `operation`
*/
export default curry(debounce);