一个创建异步防抖函数的类。
防抖确保函数仅在自上次调用指定延迟时间后才会被执行。每次新调用都会重置延迟计时器。这对于处理频繁事件(如窗口大小调整或输入更改)非常有用,您只希望在事件停止发生后执行处理程序。
与节流(节流允许在固定间隔内执行)不同,防抖会阻止任何执行,直到函数在指定的延迟时间内停止被调用。
与非异步 Debouncer 不同,此异步版本支持从防抖函数返回值为 API 调用和其他异步操作提供了理想的解决方案,您希望获得 maybeExecute 调用的结果,而不是在防抖函数内部将结果设置到状态变量中。
错误处理
状态管理
const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
const results = await searchAPI(value);
return results; // Return value is preserved
}, {
wait: 500,
onError: (error) => {
console.error('Search failed:', error);
}
});
// Called on each keystroke but only executes after 500ms of no typing
// Returns the API response directly
const results = await asyncDebouncer.maybeExecute(inputElement.value);
const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
const results = await searchAPI(value);
return results; // Return value is preserved
}, {
wait: 500,
onError: (error) => {
console.error('Search failed:', error);
}
});
// Called on each keystroke but only executes after 500ms of no typing
// Returns the API response directly
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>
fn: TFn;
fn: TFn;
key: string;
key: string;
options: AsyncDebouncerOptions<TFn>;
options: AsyncDebouncerOptions<TFn>;
readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>;
readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>;
cancel(): void
cancel(): void
取消任何待处理的执行或中止任何正在进行的执行
void
flush(): Promise<undefined | ReturnType<TFn>>
flush(): Promise<undefined | ReturnType<TFn>>
立即处理当前挂起的执行
Promise<undefined | ReturnType<TFn>>
maybeExecute(...args): Promise<undefined | ReturnType<TFn>>
maybeExecute(...args): Promise<undefined | ReturnType<TFn>>
尝试执行防抖函数。如果已有调用正在进行,它将被加入队列。
错误处理
...Parameters<TFn>
Promise<undefined | ReturnType<TFn>>
一个 Promise,它会解析为函数的返回值,如果错误被 onError 处理,则返回 undefined
防抖函数产生的错误(如果未配置 onError 处理程序)
reset(): void
reset(): void
将去抖器状态重置为其默认值
void
setOptions(newOptions): void
setOptions(newOptions): void
更新异步防抖器选项
Partial<AsyncDebouncerOptions<TFn>>
void
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。