Open History to see the last commit
1---
2id: rateLimit
3title: rateLimit
4---
5
6```ts
7function rateLimit<TFn>(fn, initialOptions): (...args) => boolean;
8```
9
10Defined in: [rate-limiter.ts:423](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/rate-limiter.ts#L423)
11
12Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
13
14This synchronous version is lighter weight and often all you need - upgrade to asyncRateLimit when you need promises, retry support, abort capabilities, or advanced error handling.
15
16Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
17- A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
18- A throttler ensures even spacing between executions, which can be better for consistent performance
19- A debouncer collapses multiple calls into one, which is better for handling bursts of events
20
21The rate limiter supports two types of windows:
22- 'fixed': A strict window that resets after the window period. All executions within the window count
23 towards the limit, and the window resets completely after the period.
24- 'sliding': A rolling window that allows executions as old ones expire. This provides a more
25 consistent rate of execution over time.
26
27State Management:
28- Uses TanStack Store for reactive state management
29- Use `initialState` to provide initial state values when creating the rate limiter
30- Use `onExecute` callback to react to function execution and implement custom logic
31- Use `onReject` callback to react to executions being rejected when rate limit is exceeded
32- The state includes execution count, execution times, and rejection count
33- State can be accessed via the underlying RateLimiter instance's `store.state` property
34- When using framework adapters (React/Solid), state is accessed from the hook's state property
35
36Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
37need to enforce a hard limit on the number of executions within a time period.
38
39## Type Parameters
40
41### TFn
42
43`TFn` *extends* [`AnyFunction`](../type-aliases/AnyFunction.md)
44
45## Parameters
46
47### fn
48
49`TFn`
50
51### initialOptions
52
53[`RateLimiterOptions`](../interfaces/RateLimiterOptions.md)\<`TFn`\>
54
55## Returns
56
57```ts
58(...args): boolean;
59```
60
61Attempts to execute the rate-limited function if within the configured limits.
62Will reject execution if the number of calls in the current window exceeds the limit.
63
64### Parameters
65
66#### args
67
68...`Parameters`\<`TFn`\>
69
70### Returns
71
72`boolean`
73
74### Example
75
76```ts
77const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
78
79// First 5 calls will return true
80rateLimiter.maybeExecute('arg1', 'arg2'); // true
81
82// Additional calls within the window will return false
83rateLimiter.maybeExecute('arg1', 'arg2'); // false
84```
85
86## Example
87
88```ts
89// Rate limit to 5 calls per minute with a sliding window
90const rateLimited = rateLimit(makeApiCall, {
91 limit: 5,
92 window: 60000,
93 windowType: 'sliding',
94 onReject: (rateLimiter) => {
95 console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
96 }
97});
98
99// First 5 calls will execute immediately
100// Additional calls will be rejected until the minute window resets
101rateLimited();
102
103// For more even execution, consider using throttle instead:
104const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
105```