一个创建异步节流函数的类。
节流限制函数执行的频率,在指定的时段内只允许执行一次。与去抖动(debouncing)不同,去抖动会在每次调用时重置延迟计时器,而节流则确保函数以固定的间隔执行,无论调用频率如何。
与非异步的Throttler不同,这个异步版本支持从节流函数返回,这使其成为API调用和其他异步操作的理想选择,当您希望从 maybeExecute 调用中获取结果,而不是在节流函数内部将结果设置到状态变量时。
这对于限制API调用频率、处理滚动/窗口大小调整事件,或者任何需要确保最大执行频率的场景都很有用。
错误处理
状态管理
const throttler = new AsyncThrottler(async (value: string) => {
const result = await saveToAPI(value);
return result; // Return value is preserved
}, {
wait: 1000,
onError: (error) => {
console.error('API call failed:', error);
}
});
// Will only execute once per second no matter how often called
// Returns the API response directly
const result = await throttler.maybeExecute(inputElement.value);
const throttler = new AsyncThrottler(async (value: string) => {
const result = await saveToAPI(value);
return result; // Return value is preserved
}, {
wait: 1000,
onError: (error) => {
console.error('API call failed:', error);
}
});
// Will only execute once per second no matter how often called
// Returns the API response directly
const result = await throttler.maybeExecute(inputElement.value);
• TFn extends AnyAsyncFunction
new AsyncThrottler<TFn>(fn, initialOptions): AsyncThrottler<TFn>
new AsyncThrottler<TFn>(fn, initialOptions): AsyncThrottler<TFn>
TFn
AsyncThrottler<TFn>
fn: TFn;
fn: TFn;
key: string;
key: string;
options: AsyncThrottlerOptions<TFn>;
options: AsyncThrottlerOptions<TFn>;
readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
readonly store: Store<Readonly<AsyncThrottlerState<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>>
const throttled = new AsyncThrottler(fn, { wait: 1000 });
// First call executes immediately
await throttled.maybeExecute('a', 'b');
// Call during wait period - gets throttled
await throttled.maybeExecute('c', 'd');
const throttled = new AsyncThrottler(fn, { wait: 1000 });
// First call executes immediately
await throttled.maybeExecute('a', 'b');
// Call during wait period - gets throttled
await throttled.maybeExecute('c', 'd');
reset(): void
reset(): void
将去抖器状态重置为其默认值
void
setOptions(newOptions): void
setOptions(newOptions): void
更新异步节流器选项
Partial<AsyncThrottlerOptions<TFn>>
void
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。