function rateLimit<TFn>(fn, initialOptions): (...args) => boolean
function rateLimit<TFn>(fn, initialOptions): (...args) => boolean
Defined in: rate-limiter.ts:404
Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
The rate limiter supports two types of windows:
State Management:
Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically need to enforce a hard limit on the number of executions within a time period.
• TFn extends AnyFunction
TFn
RateLimiterOptions<TFn>
Function
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.
...Parameters<TFn>
boolean
const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
// First 5 calls will return true
rateLimiter.maybeExecute('arg1', 'arg2'); // true
// Additional calls within the window will return false
rateLimiter.maybeExecute('arg1', 'arg2'); // false
const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
// First 5 calls will return true
rateLimiter.maybeExecute('arg1', 'arg2'); // true
// Additional calls within the window will return false
rateLimiter.maybeExecute('arg1', 'arg2'); // false
// Rate limit to 5 calls per minute with a sliding window
const rateLimited = rateLimit(makeApiCall, {
limit: 5,
window: 60000,
windowType: 'sliding',
onReject: (rateLimiter) => {
console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
}
});
// First 5 calls will execute immediately
// Additional calls will be rejected until the minute window resets
rateLimited();
// For more even execution, consider using throttle instead:
const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
// Rate limit to 5 calls per minute with a sliding window
const rateLimited = rateLimit(makeApiCall, {
limit: 5,
window: 60000,
windowType: 'sliding',
onReject: (rateLimiter) => {
console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
}
});
// First 5 calls will execute immediately
// Additional calls will be rejected until the minute window resets
rateLimited();
// For more even execution, consider using throttle instead:
const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.