// 防抖函数
function debounce(fn, wait) {
let timeout = null;
return function() {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait);
if (callNow) fn.apply(context, args);
};
}
// 节流函数
function throttle(fn, wait) {
let previous = 0;
return function() {
let context = this;
let args = arguments;
let now = new Date();
if (now - previous > wait) {
fn.apply(context, args);
previous = now;
}
};
}
// 使用场景示例
// 防抖应用于搜索框输入
let searchBox = document.getElementById('search-box');
let debouncedInput = debounce(search, 500);
searchBox.addEventListener('input', debouncedInput);
// 节流应用于鼠标移动
let mouseMove = throttle(handleMouseMove, 1000);
document.addEventListener('mousemove', mouseMove);这段代码展示了如何使用防抖和节流函数来优化事件处理。防抖确保事件处理器在 n 秒内不会被频繁触发,而节流则限制了一定时间内事件处理器的调用频率。这两种技术在输入字段的实时验证、滚动事件的处理和高频率触发的按钮点击等场景中有着广泛的应用。