-
Notifications
You must be signed in to change notification settings - Fork 0
/
throttle.js
46 lines (40 loc) · 1.16 KB
/
throttle.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
// function throttle(fn, delay) {
// let flush = true;
// let cachedArgs;
// let cachedThis;
// return function wrapper(...args) {
// if (flush === true) {
// flush = false;
// fn.apply(this, args);
// setTimeout(() => {
// flush = true;
// if (cachedArgs && cachedThis) {
// wrapper.apply(cachedArgs, cachedThis);
// }
// }, delay);
// } else {
// cachedArgs = args;
// cachedThis = this;
// return;
// }
// };
// }
function throttle(func, delay) {
let timer = null;
let startTime = Date.now();
return function() {
let curTime = Date.now();
let remaining = delay - (curTime - startTime);
const context = this;
const args = arguments;
clearTimeout(timer);
if (remaining <= 0) {
func.apply(context, args);
startTime = Date.now();
} else {
timer = setTimeout(func, remaining);
}
}
}
const func = throttle(() => console.log(Date.now()), 1000)
setInterval(() => func(), 1000)