function asyncThrottle<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
function asyncThrottle<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
Defined in: async-throttler.ts:457
Creates an async throttled function that limits how often the function can execute. The throttled function will execute at most once per wait period, even if called multiple times. If called while executing, it will wait until execution completes before scheduling the next call.
Unlike the non-async Throttler, this async version supports returning values from the throttled function, making it ideal for API calls and other async operations where you want the result of the maybeExecute call instead of setting the result on a state variable from within the throttled function.
Error Handling:
State Management:
• TFn extends AnyAsyncFunction
TFn
Function
Attempts to execute the throttled function. The execution behavior depends on the throttler options:
If enough time has passed since the last execution (>= wait period):
If within the wait period:
...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');
const throttled = asyncThrottle(async (value: string) => {
const result = await saveToAPI(value);
return result; // Return value is preserved
}, {
wait: 1000,
onError: (error) => {
console.error('API call failed:', error);
}
});
// This will execute at most once per second
// Returns the API response directly
const result = await throttled(inputElement.value);
const throttled = asyncThrottle(async (value: string) => {
const result = await saveToAPI(value);
return result; // Return value is preserved
}, {
wait: 1000,
onError: (error) => {
console.error('API call failed:', error);
}
});
// This will execute at most once per second
// Returns the API response directly
const result = await throttled(inputElement.value);
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.