- 防抖:事件持续触发,但只有当事件停止触发后n秒才执行函数。
- 节流:事件持续触发时,每n秒执行一次函数。
防抖
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秒后才能再次触发函数执行。
}, delay)
} else {
timer = setTimeout(() => {
func.apply(context, args);
}, delay)
}
return result;
};
debounced.cancel = function(){
clearTimeout(timer);
timer = null;
}
}
节流
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)
}
}
}