可以形象理解为“节约流量”防止事件高频触发
将高频触发变为低频触发
function throttle(fn, delay = 100) {
let timer = null;
return function() {
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null
}, delay)
}
}
可以形象理解为“防止抖动(手抖)”导致事件多次触发
将多次触发变为最后一次触发
function debounce(fn, delay = 100) {
let timer = null;
return function() {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null
}, delay)
}
}