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
//节流函数
//每隔一段时间触发
//第一次触发立即执行
//如果在间隔时间内触发,会在间隔末尾再执行一次
function throttle(callback, timmer) {
let isFirst = true;
let execDate = +new Date();
let throttleId;
return function () {
if (isFirst) {
callback();
execDate = +new Date();
isFirst = false;
} else {
const currentDate = +new Date();
if (currentDate - execDate >= timmer) {
callback();
execDate = + new Date();
} else {
if (throttleId) {
clearTimeout(throttleId)
};
const timeWait = execDate + timmer - (+new Date());
throttleId = setTimeout(() => {
callback();
execDate = + new Date();
}, timeWait)
}
}
}
}
查看评论