js 实现防抖
防抖的实现原理
防抖(Debounce)是一种优化高频触发事件的技术,确保事件在停止触发一段时间后才会执行回调函数。适用于输入框搜索、窗口大小调整等场景。

基础防抖函数实现
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
func: 需要防抖的实际执行函数delay: 防抖延迟时间(毫秒)- 每次调用都会清除之前的定时器,重新计时
立即执行版本
有些场景需要首次触发立即执行,后续触发才防抖:
function debounceImmediate(func, delay, immediate = true) {
let timeoutId;
return function(...args) {
const callNow = immediate && !timeoutId;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
timeoutId = null;
if (!immediate) func.apply(this, args);
}, delay);
if (callNow) func.apply(this, args);
};
}
TypeScript 实现
增加类型安全的版本:
function debounce<T extends (...args: any[]) => void>(
func: T,
delay: number
): (...args: Parameters<T>) => void {
let timeoutId: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func(...args);
}, delay);
};
}
使用示例
const handleSearch = debounce((query) => {
console.log('Searching for:', query);
// 实际搜索逻辑
}, 500);
document.getElementById('search-input').addEventListener('input', (e) => {
handleSearch(e.target.value);
});
注意事项
- 防抖函数返回的新函数需要保持原始函数的
this上下文,因此使用apply - 对于需要取消的防抖操作,可以扩展返回取消方法
- 延迟时间需要根据实际场景调整,通常搜索建议用 300-500ms,UI 调整用 100ms







