跳到主要内容

debounce()

function debounce<Func>(func, waitMilliseconds?): (this, ...args) => void;

Defined in: function/debounce.ts:29

创建一个防抖函数,确保函数在最后一次调用后延迟指定时间才执行 连续调用会重置计时器,适用于处理频繁触发的事件(如滚动、输入框输入)

Type Parameters

Type ParameterDescription
Func extends AnyFunction被防抖的函数类型

Parameters

ParameterTypeDefault valueDescription
funcFuncundefined需要防抖的函数
waitMilliseconds?number50延迟执行的毫秒数,默认为50ms

Returns

防抖后的函数

(this, ...args) => void

Examples

// 基础用法
const handleSearch = debounce((query: string) => {
console.log('搜索:', query);
}, 300);
// 输入框变化时调用
input.addEventListener('input', (e) => handleSearch(e.target.value));
// 带this上下文
const obj = {
value: 10,
getValue: debounce(function() {
return this.value;
})
};
**Note:** 防抖函数会忽略原始函数的返回值,因为它通过setTimeout异步执行
**Note:** 连续调用会重置延迟计时器,只有在停止调用后经过waitMilliseconds才会执行