js实现阻隔
实现阻隔(防抖与节流)
防抖(Debounce)和节流(Throttle)是JavaScript中常用的阻隔技术,用于优化高频事件的性能。以下是具体实现方法:
防抖(Debounce)
防抖确保函数在连续触发时只执行最后一次,或在停止触发后延迟执行。
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
使用场景:
- 搜索框输入联想
- 窗口大小调整事件
示例调用:

const handleSearch = debounce(() => {
console.log('执行搜索');
}, 500);
inputElement.addEventListener('input', handleSearch);
节流(Throttle)
节流确保函数在固定时间间隔内只执行一次。
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function(...args) {
if (!lastRan) {
func.apply(this, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if (Date.now() - lastRan >= limit) {
func.apply(this, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
使用场景:

- 滚动事件监听
- 游戏中的按键处理
示例调用:
const handleScroll = throttle(() => {
console.log('处理滚动');
}, 200);
window.addEventListener('scroll', handleScroll);
注意事项
- 防抖适用于需要等待操作结束的场景,如输入完成
- 节流适用于需要均匀分配执行次数的场景,如动画渲染
- 时间参数需要根据实际场景调整
- 使用箭头函数时需注意this绑定问题
高级变体
立即执行的防抖版本:
function debounceImmediate(func, delay) {
let timeoutId;
return function(...args) {
const callNow = !timeoutId;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
timeoutId = null;
}, delay);
if (callNow) func.apply(this, args);
};
}
带取消功能的节流:
function cancellableThrottle(func, limit) {
let lastRan;
let timeoutId;
const throttled = function(...args) {
if (!lastRan || Date.now() - lastRan >= limit) {
func.apply(this, args);
lastRan = Date.now();
} else {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
throttled.apply(this, args);
}, limit - (Date.now() - lastRan));
}
};
throttled.cancel = () => clearTimeout(timeoutId);
return throttled;
}






