Defined in: async-rate-limiter.ts:187
A class that creates an async rate-limited function.
Rate limiting is a simple approach that allows a function to execute up to a limit within a time window, then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where all executions happen immediately, followed by a complete block.
The rate limiter supports two types of windows:
Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited 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 rate-limited function.
For smoother execution patterns, consider using:
Rate limiting is best used for hard API limits or resource constraints. For UI updates or smoothing out frequent events, throttling or debouncing usually provide better user experience.
State Management:
Error Handling:
const rateLimiter = new AsyncRateLimiter(
async (id: string) => await api.getData(id),
{
limit: 5,
window: 1000,
windowType: 'sliding',
onError: (error) => {
console.error('API call failed:', error);
},
onReject: (limiter) => {
console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`);
}
}
);
// Will execute immediately until limit reached, then block
// Returns the API response directly
const data = await rateLimiter.maybeExecute('123');
const rateLimiter = new AsyncRateLimiter(
async (id: string) => await api.getData(id),
{
limit: 5,
window: 1000,
windowType: 'sliding',
onError: (error) => {
console.error('API call failed:', error);
},
onReject: (limiter) => {
console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`);
}
}
);
// Will execute immediately until limit reached, then block
// Returns the API response directly
const data = await rateLimiter.maybeExecute('123');
• TFn extends AnyAsyncFunction
new AsyncRateLimiter<TFn>(fn, initialOptions): AsyncRateLimiter<TFn>
new AsyncRateLimiter<TFn>(fn, initialOptions): AsyncRateLimiter<TFn>
Defined in: async-rate-limiter.ts:193
TFn
AsyncRateLimiter<TFn>
options: AsyncRateLimiterOptions<TFn>;
options: AsyncRateLimiterOptions<TFn>;
Defined in: async-rate-limiter.ts:191
readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>;
readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>;
Defined in: async-rate-limiter.ts:188
getMsUntilNextWindow(): number
getMsUntilNextWindow(): number
Defined in: async-rate-limiter.ts:366
Returns the number of milliseconds until the next execution will be possible For fixed windows, this is the time until the current window resets For sliding windows, this is the time until the oldest execution expires
number
getRemainingInWindow(): number
getRemainingInWindow(): number
Defined in: async-rate-limiter.ts:356
Returns the number of remaining executions allowed in the current window
number
maybeExecute(...args): Promise<undefined | ReturnType<TFn>>
maybeExecute(...args): Promise<undefined | ReturnType<TFn>>
Defined in: async-rate-limiter.ts:268
Attempts to execute the rate-limited function if within the configured limits. Will reject execution if the number of calls in the current window exceeds the limit.
Error Handling:
...Parameters<TFn>
Promise<undefined | ReturnType<TFn>>
A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
The error from the rate-limited function if no onError handler is configured
const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
// First 5 calls will return a promise that resolves with the result
const result = await rateLimiter.maybeExecute('arg1', 'arg2');
// Additional calls within the window will return undefined
const result2 = await rateLimiter.maybeExecute('arg1', 'arg2'); // undefined
const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
// First 5 calls will return a promise that resolves with the result
const result = await rateLimiter.maybeExecute('arg1', 'arg2');
// Additional calls within the window will return undefined
const result2 = await rateLimiter.maybeExecute('arg1', 'arg2'); // undefined
reset(): void
reset(): void
Defined in: async-rate-limiter.ts:377
Resets the rate limiter state
void
setOptions(newOptions): void
setOptions(newOptions): void
Defined in: async-rate-limiter.ts:208
Updates the async rate limiter options
Partial<AsyncRateLimiterOptions<TFn>>
void
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.