JS 中的防抖和节流是两种常见的事件优化方法,用于控制高频率触发事件的频率,避免出现性能问题。以下是两个比较常用的函数实现:
防抖
防抖(Debounce)的原理是:在事件被触发 n 秒后再执行回调函数,如果在这 n 秒内又被触发,则重新计时。这样可以稳定地降低回调函数的执行频率。
function debounce(fn, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
// 使用示例:
function handleInput() {
console.log('处理输入事件');
}
const debouncedHandleInput = debounce(handleInput, 500);
document.querySelector('input').addEventListener('input', debouncedHandleInput);
上面的代码中,debounce 函数接收两个参数:一个是要延迟执行的回调函数 fn,另一个是延迟时间 delay。返回值是一个新的函数,当这个新函数被调用时,会触发 fn 函数,并且自动使用 delay 毫秒的时间进行防抖。
节流
节流(Throttle)的原理是:在一段时间内只执行一次事件回调函数,其他事件被忽略。这样可以有效地减少回调函数的执行频率。
function throttle(fn, delay) {
let timer = null;
let lastTime = null;
return function(...args) {
const now = +new Date();
if (!lastTime || now - lastTime >= delay) {
fn.apply(this, args);
lastTime = now;
} else {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
lastTime = now;
}, delay - (now - lastTime));
}
};
}
// 使用示例:
function handleScroll() {
console.log('处理滚动事件');
}
const throttledHandleScroll = throttle(handleScroll, 500);
document.addEventListener('scroll', throttledHandleScroll);
上面的代码中,throttle 函数接收两个参数:一个是要处理的回调函数 fn,另一个是时间间隔 delay。在每次触发事件时,该函数会检查是否已经过去了 delay 毫秒(即 lastTime 是否被初始化),如果没过去则忽略该事件;如果已经过去,则立即执行回调函数,并更新 lastTime 的值。
如果在时间间隔内连续触发了多次事件,则使用 setTimeout 延迟到下一个 interval 执行。注意需要减去 now - lastTime 的时间差来补偿当前所耗费的时间。