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');
}, 300);
inputElement.addEventListener('input', handleSearch);
节流(Throttle)实现
节流的核心是在固定时间内只执行一次函数,稀释触发频率。适用于滚动事件、高频点击等场景。

代码示例:
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
// 使用示例
const handleScroll = throttle(() => {
console.log('Scroll event handled');
}, 200);
window.addEventListener('scroll', handleScroll);
结合防抖与节流
某些场景需要先防抖(避免初始频繁触发),后节流(保证后续稳定执行)。

代码示例:
function debounceThrottle(func, debounceTime, throttleTime) {
let lastCall = 0;
let timer;
return function(...args) {
const now = Date.now();
clearTimeout(timer);
if (now - lastCall < throttleTime) {
timer = setTimeout(() => {
lastCall = now;
func.apply(this, args);
}, debounceTime);
} else {
lastCall = now;
func.apply(this, args);
}
};
}
注意事项
- 性能影响:防抖和节流会减少函数执行次数,但需合理设置延迟时间(如搜索建议建议300ms,滚动事件建议100ms)。
- this绑定:通过
apply确保函数执行时的正确上下文。 - 取消机制:可扩展实现取消功能,例如存储
timer并提供cancel方法。
扩展取消示例:
function debounce(func, delay) {
let timer;
function debounced(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
}
debounced.cancel = () => clearTimeout(timer);
return debounced;
}






