一个创建异步防抖函数的类。
防抖确保函数仅在其最后一次调用后经过指定的延迟后才执行。 每次新的调用都会重置延迟计时器。这对于处理频繁事件(如窗口大小调整)非常有用 或输入更改,您只想在事件停止发生后执行处理程序。
与节流(允许定期执行)不同,防抖会阻止任何执行,直到 函数在指定的延迟期内停止被调用。
与非异步 Debouncer 不同,此异步版本支持从防抖函数返回值, 使其非常适合 API 调用和其他异步操作,在这些操作中,您希望获得 maybeExecute 调用的结果 而不是在防抖函数内部设置状态变量的结果。
错误处理:
const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
const results = await searchAPI(value);
return results; // 返回值被保留
}, {
wait: 500,
onError: (error) => {
console.error('搜索失败:', error);
}
});
// 在每次按键时调用,但仅在停止输入 500 毫秒后执行
// 直接返回 API 响应
const results = await asyncDebouncer.maybeExecute(inputElement.value);
const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
const results = await searchAPI(value);
return results; // 返回值被保留
}, {
wait: 500,
onError: (error) => {
console.error('搜索失败:', error);
}
});
// 在每次按键时调用,但仅在停止输入 500 毫秒后执行
// 直接返回 API 响应
const results = await asyncDebouncer.maybeExecute(inputElement.value);
• TFn extends AnyAsyncFunction
new AsyncDebouncer<TFn>(fn, initialOptions): AsyncDebouncer<TFn>
new AsyncDebouncer<TFn>(fn, initialOptions): AsyncDebouncer<TFn>
TFn
AsyncDebouncer<TFn>
cancel(): void
cancel(): void
取消任何待处理的执行或中止任何正在进行的执行
void
getEnabled(): boolean
getEnabled(): boolean
返回当前防抖器的启用状态
boolean
getErrorCount(): number
getErrorCount(): number
返回函数出错的次数
number
getIsExecuting(): boolean
getIsExecuting(): boolean
如果当前有执行正在进行,则返回 true
boolean
getIsPending(): boolean
getIsPending(): boolean
如果存在排队等待尾随执行的待处理执行,则返回 true
boolean
getLastResult(): undefined | ReturnType<TFn>
getLastResult(): undefined | ReturnType<TFn>
返回防抖函数的最后结果
undefined | ReturnType<TFn>
getOptions(): AsyncDebouncerOptions<TFn>
getOptions(): AsyncDebouncerOptions<TFn>
返回当前防抖器选项
getSettleCount(): number
getSettleCount(): number
返回函数已完成(完成或出错)的次数
number
getSuccessCount(): number
getSuccessCount(): number
返回函数已成功执行的次数
number
getWait(): number
getWait(): number
返回当前防抖器的等待状态
number
maybeExecute(...args): Promise<undefined | ReturnType<TFn>>
maybeExecute(...args): Promise<undefined | ReturnType<TFn>>
尝试执行防抖函数。 如果已有调用正在进行,则会将其排队。
错误处理:
...Parameters<TFn>
Promise<undefined | ReturnType<TFn>>
一个 Promise,它解析为函数的返回值,如果发生错误并由 onError 处理,则解析为 undefined
如果未配置 onError 处理程序,则抛出防抖函数的错误
setOptions(newOptions): void
setOptions(newOptions): void
更新防抖器选项
Partial<AsyncDebouncerOptions<TFn>>
void