- 防抖:事件持續(xù)觸發(fā)荷憋,但只有當事件停止觸發(fā)后n秒才執(zhí)行函數(shù)蜀涨。
- 節(jié)流:事件持續(xù)觸發(fā)時炕婶,每n秒執(zhí)行一次函數(shù)侍瑟。
防抖
const debounce = function (func, delay, immediate = false) {
let timer,
result,
callNow = true;
const debounced = function () {
const context = this;
const args = arguments;
if (timer) clearTimeout(timer);
if (immediate) {
if(callNow) result = func.apply(context, args);
callNow = false;
timer = setTimeout(() => {
callNow = true; // 過n秒后才能再次觸發(fā)函數(shù)執(zhí)行唐片。
}, delay)
} else {
timer = setTimeout(() => {
func.apply(context, args);
}, delay)
}
return result;
};
debounced.cancel = function(){
clearTimeout(timer);
timer = null;
}
}
節(jié)流
const throttle = function(func, delay) {
let timer,
prev = 0;
return function(){
const context = this;
const args = arguments;
const now = +new Date();
const remaining = delay - (now - prev);
if (remaining <= 0) {
prev = now;
func.apply(context, args);
} else if(!timer) {
timer = setTimeout(() => {
prev = +new Date();
timer = null;
func.apply(context, args);
}, remaining)
}
}
}