Skip to content
Source
Sign inSign up
TanStack/pacer
Open History to see the last commit

AsyncThrottler.md

319 lines7.8 KB

1---
2id: AsyncThrottler
3title: AsyncThrottler
4---
5​
6Defined in: [async-throttler.ts:230](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L230)
7​
8A class that creates an async throttled function.
9​
10Async vs Sync Versions:
11The async version provides advanced features over the sync Throttler:
12- Returns promises that can be awaited for throttled function results
13- Built-in retry support via AsyncRetryer integration
14- Abort support to cancel in-flight executions
15- Cancel support to prevent pending executions from starting
16- Comprehensive error handling with onError callbacks and throwOnError control
17- Detailed execution tracking (success/error/settle counts)
18- Waits for ongoing executions to complete before scheduling the next one
19​
20The sync Throttler is lighter weight and simpler when you don't need async features,
21return values, or execution control.
22​
23What is Throttling?
24Throttling limits how often a function can be executed, allowing only one execution within a specified time window.
25Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
26regular interval regardless of how often it's called.
27​
28This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to
29ensure a maximum execution frequency.
30​
31Error Handling:
32- If an `onError` handler is provided, it will be called with the error and throttler instance
33- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
34- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
35- Both onError and throwOnError can be used together - the handler will be called before any error is thrown
36- The error state can be checked using the underlying AsyncThrottler instance
37​
38State Management:
39- Uses TanStack Store for reactive state management
40- Use `initialState` to provide initial state values when creating the async throttler
41- Use `onSuccess` callback to react to successful function execution and implement custom logic
42- Use `onError` callback to react to function execution errors and implement custom error handling
43- Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
44- The state includes error count, execution status, last execution time, and success/settle counts
45- State can be accessed via `asyncThrottler.store.state` when using the class directly
46- When using framework adapters (React/Solid), state is accessed from `asyncThrottler.state`
47​
48## Example
49​
50```ts
51const throttler = new AsyncThrottler(async (value: string) => {
52 const result = await saveToAPI(value);
53 return result; // Return value is preserved
54}, {
55 wait: 1000,
56 onError: (error) => {
57 console.error('API call failed:', error);
58 }
59});
60​
61// Will only execute once per second no matter how often called
62// Returns the API response directly
63const result = await throttler.maybeExecute(inputElement.value);
64```
65​
66## Type Parameters
67​
68### TFn
69​
70`TFn` *extends* [`AnyAsyncFunction`](../type-aliases/AnyAsyncFunction.md)
71​
72## Constructors
73​
74### Constructor
75​
76```ts
77new AsyncThrottler<TFn>(fn, initialOptions): AsyncThrottler<TFn>;
78```
79​
80Defined in: [async-throttler.ts:241](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L241)
81​
82#### Parameters
83​
84##### fn
85​
86`TFn`
87​
88##### initialOptions
89​
90[`AsyncThrottlerOptions`](../interfaces/AsyncThrottlerOptions.md)\<`TFn`\>
91​
92#### Returns
93​
94`AsyncThrottler`\<`TFn`\>
95​
96## Properties
97​
98### asyncRetryers
99​
100```ts
101asyncRetryers: Map<number, AsyncRetryer<TFn>>;
102```
103​
104Defined in: [async-throttler.ts:236](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L236)
105​
106***
107​
108### fn
109​
110```ts
111fn: TFn;
112```
113​
114Defined in: [async-throttler.ts:242](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L242)
115​
116***
117​
118### key
119​
120```ts
121key: string | undefined;
122```
123​
124Defined in: [async-throttler.ts:234](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L234)
125​
126***
127​
128### options
129​
130```ts
131options: AsyncThrottlerOptions<TFn>;
132```
133​
134Defined in: [async-throttler.ts:235](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L235)
135​
136***
137​
138### store
139​
140```ts
141readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
142```
143​
144Defined in: [async-throttler.ts:231](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L231)
145​
146## Methods
147​
148### abort()
149​
150```ts
151abort(): void;
152```
153​
154Defined in: [async-throttler.ts:534](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L534)
155​
156Aborts all ongoing executions with the internal abort controllers.
157Does NOT cancel any pending execution that have not started yet.
158​
159#### Returns
160​
161`void`
162​
163***
164​
165### cancel()
166​
167```ts
168cancel(): void;
169```
170​
171Defined in: [async-throttler.ts:544](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L544)
172​
173Cancels any pending execution that have not started yet.
174Does NOT abort any execution already in progress.
175​
176#### Returns
177​
178`void`
179​
180***
181​
182### flush()
183​
184```ts
185flush(): Promise<Awaited<ReturnType<TFn>> | undefined>;
186```
187​
188Defined in: [async-throttler.ts:463](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L463)
189​
190Processes the current pending execution immediately
191​
192#### Returns
193​
194`Promise`\<`Awaited`\<`ReturnType`\<`TFn`\>\> \| `undefined`\>
195​
196***
197​
198### getAbortSignal()
199​
200```ts
201getAbortSignal(maybeExecuteCount?): AbortSignal | null;
202```
203​
204Defined in: [async-throttler.ts:524](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L524)
205​
206Returns the AbortSignal for a specific execution.
207If no maybeExecuteCount is provided, returns the signal for the most recent execution.
208Returns null if no execution is found or not currently executing.
209​
210#### Parameters
211​
212##### maybeExecuteCount?
213​
214`number`
215​
216Optional specific execution to get signal for
217​
218#### Returns
219​
220`AbortSignal` \| `null`
221​
222#### Example
223​
224```typescript
225const throttler = new AsyncThrottler(
226 async (data: string) => {
227 const signal = throttler.getAbortSignal()
228 if (signal) {
229 const response = await fetch('/api/save', {
230 method: 'POST',
231 body: data,
232 signal
233 })
234 return response.json()
235 }
236 },
237 { wait: 1000 }
239```
240​
241***
242​
243### maybeExecute()
244​
245```ts
246maybeExecute(...args): Promise<Awaited<ReturnType<TFn>> | undefined>;
247```
248​
249Defined in: [async-throttler.ts:337](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L337)
250​
251Attempts to execute the throttled function. The execution behavior depends on the throttler options:
252​
253- If enough time has passed since the last execution (>= wait period):
254 - With leading=true: Executes immediately
255 - With leading=false: Waits for the next trailing execution
256​
257- If within the wait period:
258 - With trailing=true: Schedules execution for end of wait period
259 - With trailing=false: Drops the execution
260​
261#### Parameters
262​
263##### args
264​
265...`Parameters`\<`TFn`\>
266​
267#### Returns
268​
269`Promise`\<`Awaited`\<`ReturnType`\<`TFn`\>\> \| `undefined`\>
270​
271#### Example
272​
273```ts
274const throttled = new AsyncThrottler(fn, { wait: 1000 });
275​
276// First call executes immediately
277await throttled.maybeExecute('a', 'b');
278​
279// Call during wait period - gets throttled
280await throttled.maybeExecute('c', 'd');
281```
282​
283***
284​
285### reset()
286​
287```ts
288reset(): void;
289```
290​
291Defined in: [async-throttler.ts:558](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L558)
292​
293Resets the debouncer state to its default values
294​
295#### Returns
296​
297`void`
298​
299***
300​
301### setOptions()
302​
303```ts
304setOptions(newOptions): void;
305```
306​
307Defined in: [async-throttler.ts:269](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L269)
308​
309Updates the async throttler options
310​
311#### Parameters
312​
313##### newOptions
314​
315`Partial`\<[`AsyncThrottlerOptions`](../interfaces/AsyncThrottlerOptions.md)\<`TFn`\>\>
316​
317#### Returns
318​
319`void`