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

AsyncDebouncer.md

305 lines7.4 KB

1---
2id: AsyncDebouncer
3title: AsyncDebouncer
4---
5​
6Defined in: [async-debouncer.ts:218](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L218)
7​
8A class that creates an async debounced function.
9​
10Async vs Sync Versions:
11The async version provides advanced features over the sync Debouncer:
12- Returns promises that can be awaited for debounced 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​
19The sync Debouncer is lighter weight and simpler when you don't need async features,
20return values, or execution control.
21​
22What is Debouncing?
23Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
24Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
25or input changes where you only want to execute the handler after the events have stopped occurring.
26​
27Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
28the function stops being called for the specified delay period.
29​
30Error Handling:
31- If an `onError` handler is provided, it will be called with the error and debouncer instance
32- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
33- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
34- Both onError and throwOnError can be used together - the handler will be called before any error is thrown
35- The error state can be checked using the underlying store
36​
37State Management:
38- The debouncer uses a reactive store for state management
39- Use `initialState` to provide initial state values when creating the async debouncer
40- The state includes canLeadingExecute, error count, execution status, and success/settle counts
41- State can be accessed via the `store` property and its `state` getter
42- The store is reactive and will notify subscribers of state changes
43​
44## Example
45​
46```ts
47const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
48 const results = await searchAPI(value);
49 return results; // Return value is preserved
50}, {
51 wait: 500,
52 onError: (error) => {
53 console.error('Search failed:', error);
54 }
55});
56​
57// Called on each keystroke but only executes after 500ms of no typing
58// Returns the API response directly
59const results = await asyncDebouncer.maybeExecute(inputElement.value);
60```
61​
62## Type Parameters
63​
64### TFn
65​
66`TFn` *extends* [`AnyAsyncFunction`](../type-aliases/AnyAsyncFunction.md)
67​
68## Constructors
69​
70### Constructor
71​
72```ts
73new AsyncDebouncer<TFn>(fn, initialOptions): AsyncDebouncer<TFn>;
74```
75​
76Defined in: [async-debouncer.ts:229](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L229)
77​
78#### Parameters
79​
80##### fn
81​
82`TFn`
83​
84##### initialOptions
85​
86[`AsyncDebouncerOptions`](../interfaces/AsyncDebouncerOptions.md)\<`TFn`\>
87​
88#### Returns
89​
90`AsyncDebouncer`\<`TFn`\>
91​
92## Properties
93​
94### asyncRetryers
95​
96```ts
97asyncRetryers: Map<number, AsyncRetryer<TFn>>;
98```
99​
100Defined in: [async-debouncer.ts:224](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L224)
101​
102***
103​
104### fn
105​
106```ts
107fn: TFn;
108```
109​
110Defined in: [async-debouncer.ts:230](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L230)
111​
112***
113​
114### key
115​
116```ts
117key: string | undefined;
118```
119​
120Defined in: [async-debouncer.ts:222](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L222)
121​
122***
123​
124### options
125​
126```ts
127options: AsyncDebouncerOptions<TFn>;
128```
129​
130Defined in: [async-debouncer.ts:223](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L223)
131​
132***
133​
134### store
135​
136```ts
137readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>;
138```
139​
140Defined in: [async-debouncer.ts:219](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L219)
141​
142## Methods
143​
144### abort()
145​
146```ts
147abort(): void;
148```
149​
150Defined in: [async-debouncer.ts:470](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L470)
151​
152Aborts all ongoing executions with the internal abort controllers.
153Does NOT cancel any pending execution that have not started yet.
154​
155#### Returns
156​
157`void`
158​
159***
160​
161### cancel()
162​
163```ts
164cancel(): void;
165```
166​
167Defined in: [async-debouncer.ts:482](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L482)
168​
169Cancels any pending execution that have not started yet.
170Does NOT abort any execution already in progress.
171​
172#### Returns
173​
174`void`
175​
176***
177​
178### flush()
179​
180```ts
181flush(): Promise<Awaited<ReturnType<TFn>> | undefined>;
182```
183​
184Defined in: [async-debouncer.ts:405](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L405)
185​
186Processes the current pending execution immediately
187​
188#### Returns
189​
190`Promise`\<`Awaited`\<`ReturnType`\<`TFn`\>\> \| `undefined`\>
191​
192***
193​
194### getAbortSignal()
195​
196```ts
197getAbortSignal(maybeExecuteCount?): AbortSignal | null;
198```
199​
200Defined in: [async-debouncer.ts:460](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L460)
201​
202Returns the AbortSignal for a specific execution.
203If no maybeExecuteCount is provided, returns the signal for the most recent execution.
204Returns null if no execution is found or not currently executing.
205​
206#### Parameters
207​
208##### maybeExecuteCount?
209​
210`number`
211​
212Optional specific execution to get signal for
213​
214#### Returns
215​
216`AbortSignal` \| `null`
217​
218#### Example
219​
220```typescript
221const debouncer = new AsyncDebouncer(
222 async (searchTerm: string) => {
223 const signal = debouncer.getAbortSignal()
224 if (signal) {
225 const response = await fetch(`/api/search?q=${searchTerm}`, { signal })
226 return response.json()
227 }
228 },
229 { wait: 300 }
231```
232​
233***
234​
235### maybeExecute()
236​
237```ts
238maybeExecute(...args): Promise<Awaited<ReturnType<TFn>> | undefined>;
239```
240​
241Defined in: [async-debouncer.ts:317](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L317)
242​
243Attempts to execute the debounced function.
244If a call is already in progress, it will be queued.
245​
246Error Handling:
247- If the debounced function throws and no `onError` handler is configured,
248 the error will be thrown from this method.
249- If an `onError` handler is configured, errors will be caught and passed to the handler,
250 and this method will return undefined.
251- The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
252​
253#### Parameters
254​
255##### args
256​
257...`Parameters`\<`TFn`\>
258​
259#### Returns
260​
261`Promise`\<`Awaited`\<`ReturnType`\<`TFn`\>\> \| `undefined`\>
262​
263A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
264​
265#### Throws
266​
267The error from the debounced function if no onError handler is configured
268​
269***
270​
271### reset()
272​
273```ts
274reset(): void;
275```
276​
277Defined in: [async-debouncer.ts:490](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L490)
278​
279Resets the debouncer state to its default values
280​
281#### Returns
282​
283`void`
284​
285***
286​
287### setOptions()
288​
289```ts
290setOptions(newOptions): void;
291```
292​
293Defined in: [async-debouncer.ts:257](https://github.com/TanStack/pacer/blob/main/packages/pacer/src/async-debouncer.ts#L257)
294​
295Updates the async debouncer options
296​
297#### Parameters
298​
299##### newOptions
300​
301`Partial`\<[`AsyncDebouncerOptions`](../interfaces/AsyncDebouncerOptions.md)\<`TFn`\>\>
302​
303#### Returns
304​
305`void`