blob: f6e15f9fdde6a09dc7cd0a3853449f70a7ea3e3c (
plain)
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
|
function debounce(func, n) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(func, n, ...args);
};
}
function throttle(func, n) {
let throttling = false;
let last_args = null;
let last_call = Date.now();
let timeout = null;
return (...args) => {
if (!throttling) {
last_call = Date.now();
if (last_args) {
func.apply(this, last_args);
last_args = null;
} else {
func(...args);
}
throttling = true;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(
() => {
throttling = false;
if (last_args) {
func.apply(this, last_args);
}
},
n - (Date.now() - last_call),
);
} else {
last_args = args;
}
};
}
module.exports = {
debounce,
throttle,
};
|