防抖(debounce)和节流(throttle)都是用于控制函数执行频率的方法,可以在函数被频繁触发时进行限制,并优化性能。
防抖(debounce): 防抖的实现原理是在函数被触发后,设置一个定时器,在指定的时间内如果函数没再次触发,则执行该函数。如果函数在指定的时间内又被触发,则重新计时,直到定时器计时结束后执行一次函数。
下面是一个使用防抖的示例代码:
function debounce(func, delay) {
let timerId;
return function(...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
function handleInput() {
// 处理输入事件的逻辑
}
const debouncedHandleInput = debounce(handleInput, 500);
input.addEventListener('input', debouncedHandleInput);
节流(throttle): 节流的实现原理是在函数被触发后,设置一个定时器,在指定的时间间隔内只执行一次该函数。如果函数在指定的时间间隔内再次触发,则忽略该次触发,直到定时器计时结束后再次执行函数。
下面是一个使用节流的示例代码:
function throttle(func, delay) {
let timerId;
let lastCallTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastCallTime >= delay) {
func.apply(this, args);
lastCallTime = now;
} else {
clearTimeout(timerId);
timerId = setTimeout(() => {
func.apply(this, args);
lastCallTime = now;
}, delay);
}
};
}
function handleScroll() {
// 处理滚动事件的逻辑
}
const throttledHandleScroll = throttle(handleScroll, 500);
window.addEventListener('scroll', throttledHandleScroll);
上述代码中的debounce
和throttle
函数接受两个参数:要执行的函数和时间间隔。返回一个新的函数,该函数会限制原函数的触发频率。
使用防抖和节流可以提升页面性能,避免不必要的函数执行,特别是在一些涉及频繁触发事件(如输入框输入、滚动等)的场景中。