只记录简单实现方法、用以明白原理
防抖
debounce,去抖动。策略是当事件被触发时,设定一个周期延迟执行动作,若期间又被触发,则重新设定周期,直到周期结束,执行动作。这是 debounce 的基本思想,在后期又扩展了前缘 debounce,即执行动作在前,然后设定周期,周期内有事件被触发,不执行动作,且周期重新设定
// 暴力版:定时器期间,有新操作时,清空旧定时器,重设新定时器
var debounce = (fn, wait) => {
let timer, timeStamp=0;
let context, args;
let run = ()=>{timer= setTimeout(()=>{fn.apply(context,args);
},wait);
}
let clean = () => {clearTimeout(timer);
}
return function(){
context=this;
args=arguments;
let now = (new Date()).getTime();
if(now-timeStamp < wait){console.log('reset',now);
clean(); // clear running timer
run(); // reset new timer from current time}else{console.log('set',now);
run(); // last timer alreay executed, set a new timer}
timeStamp=now;
}
}
节流
throttling,节流的策略是,固定周期内,只执行一次动作,若有新事件触发,不执行。周期结束后,又有事件触发,开始新的周期。节流策略也分前缘和延迟两种。与 debounce 类似,延迟是指 周期结束后执行动作,前缘是指执行动作后再开始周期。
简单版:定时器期间,只执行最后一次操作
var throttling = (fn, wait) => {
let timer;
let context, args;
let run = () => {timer=setTimeout(()=>{fn.apply(context,args);
clearTimeout(timer);
timer=null;
},wait);
}
return function () {
context=this;
args=arguments;
if(!timer){console.log("throttle, set");
run();}else{console.log("throttle, ignore");
}
}
}