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

asyncDebounce.md

122 lines4.6 KB

1---
2id: asyncDebounce
3title: asyncDebounce
4---
5​
6```ts
7function asyncDebounce<TFn>(fn, initialOptions): (...args) => Promise<Awaited<ReturnType<TFn>> | undefined>;
8```
9​
10Defined in: [async-debouncer.ts:560](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L560)
11​
12Creates an async debounced function that delays execution until after a specified wait time.
13The debounced function will only execute once the wait period has elapsed without any new calls.
14If called again during the wait period, the timer resets and a new wait period begins.
15​
16Async vs Sync Versions:
17The async version provides advanced features over the sync debounce function:
18- Returns promises that can be awaited for debounced 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​
25The sync debounce function is lighter weight and simpler when you don't need async features,
26return values, or execution control.
27​
28What is Debouncing?
29Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
30Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
31or input changes where you only want to execute the handler after the events have stopped occurring.
32​
33Configuration Options:
34- `wait`: Delay in milliseconds to wait after the last call (required)
35- `leading`: Execute on the leading edge of the timeout (default: false)
36- `trailing`: Execute on the trailing edge of the timeout (default: true)
37- `enabled`: Whether the debouncer is enabled (default: true)
38- `asyncRetryerOptions`: Configure retry behavior for executions
39​
40Error Handling:
41- If an `onError` handler is provided, it will be called with the error and debouncer instance
42- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
43- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
44- The error state can be checked using the underlying AsyncDebouncer instance
45- Both onError and throwOnError can be used together - the handler will be called before any error is thrown
46​
47State Management:
48- Uses TanStack Store for reactive state management
49- Use `initialState` to provide initial state values when creating the async debouncer
50- Use `onSuccess` callback to react to successful function execution and implement custom logic
51- Use `onError` callback to react to function execution errors and implement custom error handling
52- Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
53- The state includes canLeadingExecute, error count, execution status, and success/settle counts
54- State can be accessed via `asyncDebouncer.store.state` when using the class directly
55- When using framework adapters (React/Solid), state is accessed from `asyncDebouncer.state`
56​
57## Type Parameters
58​
59### TFn
60​
61`TFn` *extends* [`AnyAsyncFunction`](../type-aliases/AnyAsyncFunction.md)
62​
63## Parameters
64​
65### fn
66​
67`TFn`
68​
69### initialOptions
70​
71[`AsyncDebouncerOptions`](../interfaces/AsyncDebouncerOptions.md)\<`TFn`\>
72​
73## Returns
74​
75```ts
76(...args): Promise<Awaited<ReturnType<TFn>> | undefined>;
77```
78​
79Attempts to execute the debounced function.
80If a call is already in progress, it will be queued.
81​
82Error Handling:
83- If the debounced function throws and no `onError` handler is configured,
84 the error will be thrown from this method.
85- If an `onError` handler is configured, errors will be caught and passed to the handler,
86 and this method will return undefined.
87- The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
88​
89### Parameters
90​
91#### args
92​
93...`Parameters`\<`TFn`\>
94​
95### Returns
96​
97`Promise`\<`Awaited`\<`ReturnType`\<`TFn`\>\> \| `undefined`\>
98​
99A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
100​
101### Throws
102​
103The error from the debounced function if no onError handler is configured
104​
105## Example
106​
107```ts
108const debounced = asyncDebounce(async (value: string) => {
109 const result = await saveToAPI(value);
110 return result; // Return value is preserved
111}, {
112 wait: 1000,
113 onError: (error) => {
114 console.error('API call failed:', error);
115 },
116 throwOnError: true // Will both log the error and throw it
117});
118​
119// Will only execute once, 1 second after the last call
120// Returns the API response directly
121const result = await debounced("third");
122```