js中防抖和节流实现
防抖(Debounce)实现
防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟期间再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
使用示例:
const handleSearch = debounce(() => {
console.log('Search triggered');
}, 500);
inputElement.addEventListener('input', handleSearch);
节流(Throttle)实现
节流的核心思想是在固定时间间隔内只执行一次回调函数。适用于滚动事件、高频点击等场景。
时间戳版本(立即执行):
function throttle(func, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
func.apply(this, args);
lastTime = now;
}
};
}
定时器版本(延迟执行):
function throttle(func, delay) {
let timer = null;
return function(...args) {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, delay);
}
};
}
组合版本(首尾都执行):
function throttle(func, delay) {
let timer = null;
let lastTime = 0;
return function(...args) {
const now = Date.now();
const remaining = delay - (now - lastTime);
if (remaining <= 0) {
if (timer) {
clearTimeout(timer);
timer = null;
}
func.apply(this, args);
lastTime = now;
} else if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
lastTime = Date.now();
}, remaining);
}
};
}
使用示例:
const handleScroll = throttle(() => {
console.log('Scroll event handled');
}, 200);
window.addEventListener('scroll', handleScroll);
关键区别
防抖在连续触发时只执行最后一次,节流在固定时间间隔内必定执行一次。实际选择取决于具体场景需求。







