const throttle = (fn, time = 1000, ...res) => {
let runType = true;
return () => {
if (runType) {
runType = false;
let setTime=setTimeout(() => {
fn(...res);
runType = true;
clearTimeout(setTime);
}, time);
}
};
};
const throttle2=(fn,time=1000,...res)=>{
let currentTime=null,lastTime=+new Date();
return ()=>{
currentTime=+new Date();
if(currentTime>=lastTime+time){
fn(...res);
lastTime=currentTime;
}
}
}
都知道计时器是宏任务,所有实际有一定误差。两种方式误差相差不大,如测试单个计时器测试会提高准确率
setInterval(throttle((e)=>{
console.log('----throttle----------',+new Date());
}),100)
setInterval(throttle2((e)=>{
console.log('----throttle2----------',+new Date());
}),100)