function rateLimit<TFn>(fn, initialOptions): (...args) => boolean
function rateLimit<TFn>(fn, initialOptions): (...args) => boolean
定义于: rate-limiter.ts:404
创建一个速率限制函数,该函数将在指定的时间窗口内最多执行提供的函数次数。
请注意,与节流(throttling)或防抖(debouncing)相比,速率限制是一种更简单的执行控制形式。
速率限制器支持两种类型的窗口
状态管理
如果您需要更智能的执行控制,请考虑使用 throttle() 或 debounce()。当您特别需要强制执行在特定时间段内的执行次数硬限制时,请使用速率限制。
• TFn extends AnyFunction
TFn
RateLimiterOptions<TFn>
Function
尝试在配置的限制内执行速率限制函数。如果当前窗口中的调用次数超过限制,则会拒绝执行。
...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
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。