防抖
多次事件觸發(fā)后、事件處理函數(shù)只執(zhí)行一次,并且是在觸發(fā)操作結(jié)束時執(zhí)行
function debounce(method,delay) {
let timer = null;
return function () {
let self = this,
args = arguments;
timer && clearTimeout(timer);
timer = setTimeout(function () {
method.apply(self,args);
},delay);
}
}
節(jié)流
觸發(fā)函數(shù)事件后,短時間內(nèi)無法連續(xù)調(diào)用,只有執(zhí)行完上一次的函數(shù)后,過了規(guī)定時間才可以調(diào)用下一次
function throttle(method, mustRunDelay) {
let timer,
args = arguments,
start;
return function loop() {
let self = this;
let now = Date.now();
if(!start){
start = now;
}
if(timer){
clearTimeout(timer);
}
if(now - start >= mustRunDelay){
method.apply(self, args);
start = now;
}else {
timer = setTimeout(function () {
loop.apply(self, args);
}, 50);
}
}
}
延時操作處理函數(shù)、若設定的延時到來之前、再次觸發(fā)函數(shù)、則清除上一次的延時操作定時器、重新定時