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

asyncThrottle.md

128 lines4.6 KB

1---
2id: asyncThrottle
3title: asyncThrottle
4---
5​
6```ts
7function asyncThrottle<TFn>(fn, initialOptions): (...args) => Promise<Awaited<ReturnType<TFn>> | undefined>;
8```
9​
10Defined in: [async-throttler.ts:628](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-throttler.ts#L628)
11​
12Creates an async throttled function that limits how often the function can execute.
13The throttled function will execute at most once per wait period, even if called multiple times.
14If called while executing, it will wait until execution completes before scheduling the next call.
15​
16Async vs Sync Versions:
17The async version provides advanced features over the sync throttle function:
18- Returns promises that can be awaited for throttled function results
19- Built-in retry support via AsyncRetryer integration
20- Abort support to cancel in-flight executions
21- Cancel support to prevent pending executions from starting
22- Comprehensive error handling with onError callbacks and throwOnError control
23- Detailed execution tracking (success/error/settle counts)
24- Waits for ongoing executions to complete before scheduling the next one
25​
26The sync throttle function is lighter weight and simpler when you don't need async features,
27return values, or execution control.
28​
29What is Throttling?
30Throttling limits how often a function can be executed, allowing only one execution within a specified time window.
31Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
32regular interval regardless of how often it's called.
33​
34Configuration Options:
35- `wait`: Time window in milliseconds during which the function can only execute once (required)
36- `leading`: Execute immediately when called (default: true)
37- `trailing`: Execute on the trailing edge of the wait period (default: true)
38- `enabled`: Whether the throttler is enabled (default: true)
39- `asyncRetryerOptions`: Configure retry behavior for executions
40​
41Error Handling:
42- If an `onError` handler is provided, it will be called with the error and throttler instance
43- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
44- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
45- Both onError and throwOnError can be used together - the handler will be called before any error is thrown
46- The error state can be checked using the underlying AsyncThrottler instance
47​
48State Management:
49- Uses TanStack Store for reactive state management
50- Use `initialState` to provide initial state values when creating the async throttler
51- Use `onSuccess` callback to react to successful function execution and implement custom logic
52- Use `onError` callback to react to function execution errors and implement custom error handling
53- Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
54- The state includes error count, execution status, last execution time, and success/settle counts
55- State can be accessed via the underlying AsyncThrottler instance's `store.state` property
56- When using framework adapters (React/Solid), state is accessed from the hook's state property
57​
58## Type Parameters
59​
60### TFn
61​
62`TFn` *extends* [`AnyAsyncFunction`](../type-aliases/AnyAsyncFunction.md)
63​
64## Parameters
65​
66### fn
67​
68`TFn`
69​
70### initialOptions
71​
72[`AsyncThrottlerOptions`](../interfaces/AsyncThrottlerOptions.md)\<`TFn`\>
73​
74## Returns
75​
76```ts
77(...args): Promise<Awaited<ReturnType<TFn>> | undefined>;
78```
79​
80Attempts to execute the throttled function. The execution behavior depends on the throttler options:
81​
82- If enough time has passed since the last execution (>= wait period):
83 - With leading=true: Executes immediately
84 - With leading=false: Waits for the next trailing execution
85​
86- If within the wait period:
87 - With trailing=true: Schedules execution for end of wait period
88 - With trailing=false: Drops the execution
89​
90### Parameters
91​
92#### args
93​
94...`Parameters`\<`TFn`\>
95​
96### Returns
97​
98`Promise`\<`Awaited`\<`ReturnType`\<`TFn`\>\> \| `undefined`\>
99​
100### Example
101​
102```ts
103const throttled = new AsyncThrottler(fn, { wait: 1000 });
104​
105// First call executes immediately
106await throttled.maybeExecute('a', 'b');
107​
108// Call during wait period - gets throttled
109await throttled.maybeExecute('c', 'd');
110```
111​
112## Example
113​
114```ts
115const throttled = asyncThrottle(async (value: string) => {
116 const result = await saveToAPI(value);
117 return result; // Return value is preserved
118}, {
119 wait: 1000,
120 onError: (error) => {
121 console.error('API call failed:', error);
122 }
123});
124​
125// This will execute at most once per second
126// Returns the API response directly
127const result = await throttled(inputElement.value);
128```