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

debouncing.md

247 lines8.5 KB

1---
2title: Vanilla Debouncing Guide
3id: debouncing
4---
5​
6Debouncing delays a function until calls have stopped for a configured amount of time. Each new call restarts the timer. With the default settings, only the most recent call executes, using its arguments.
7​
8Use debouncing when intermediate calls can be discarded and the final value is what matters. Search inputs, form validation, autosave, and resize handling are common examples.
9​
10## How debouncing works
11​
12The timeline below shows calls arriving in bursts. Every call resets the timer. The final call in each burst executes after three ticks of inactivity.
13​
14```text
15Debouncing (wait: 3 ticks)
16Timeline: [1 second per tick]
17Calls: ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️
18Executed: ❌ ❌ ❌ ❌ ❌ ❌ ❌ ❌ ⏳ -> ✅ ❌ ⏳ -> ✅
19 [================================================================]
20 ^ Executes here after
21 3 ticks of no calls
22​
23 [Burst of calls] [More calls] [Wait] [New burst]
24 No execution Resets timer Execute Reset and execute
25```
26​
27Only the latest call in each burst executes. All earlier calls are discarded.
28​
29Debouncing is intentionally lossy. If every operation must run, use [queuing](./queuing.md) instead.
30​
31## When to use debouncing
32​
33Choose debouncing when:
34​
35- You want to wait until activity stops.
36- Only the latest arguments matter.
37- Repeating the operation for every event would waste work.
38- A short delay is acceptable.
39​
40Choose another utility when:
41​
42- Work should run at a steady interval while activity continues. Use [throttling](./throttling.md).
43- A fixed number of calls may run within a time window. Use [rate limiting](./rate-limiting.md).
44- Every operation must eventually run. Use [queuing](./queuing.md).
45- Several items should be processed together. Use [batching](./batching.md).
46- You need to await a result, handle errors, retry, or abort in-flight work. Use [async debouncing](./async-debouncing.md).
47​
48## Using debouncing in TanStack Pacer
49​
50TanStack Pacer provides two core debouncing APIs:
51​
52- `debounce` returns a debounced function.
53- `Debouncer` exposes the debounced function plus lifecycle methods and observable state.
54​
55### Convenience function
56​
57Use `debounce` when you only need to invoke the debounced function:
58​
59```ts
60import { debounce } from '@tanstack/pacer'
61​
62const search = debounce(
63 (query: string) => {
64 updateSearchResults(query)
65 },
66 { wait: 500 },
68​
69search('t')
70search('ta')
71search('tanstack')
72​
73// After 500ms without another call:
74// updateSearchResults('tanstack')
75```
76​
77The returned function does not expose methods such as `cancel()` or `flush()`. Use the class API when you need that control.
78​
79### Class API
80​
81Use `Debouncer` when you need lifecycle methods, dynamic options, callbacks, or state:
82​
83```ts
84import { Debouncer } from '@tanstack/pacer'
85​
86const searchDebouncer = new Debouncer(
87 (query: string) => {
88 updateSearchResults(query)
89 },
90 { wait: 500 },
92​
93searchDebouncer.maybeExecute('tanstack')
94​
95console.log(searchDebouncer.store.state.isPending) // true
96​
97// Execute the pending call now instead of waiting.
98searchDebouncer.flush()
99```
100​
101Both the function returned by `debounce` and `Debouncer.maybeExecute()` return `void`. Use `AsyncDebouncer` when the caller needs to await the wrapped function's result.
102​
103### Results and errors
104​
105The synchronous debouncer does not retain the wrapped function's return value or catch its errors. An error from a leading execution propagates from `maybeExecute()`. A trailing execution runs later from a timer, so its errors cannot be caught around the earlier `maybeExecute()` call.
106​
107Handle synchronous errors inside the wrapped function. Use [async debouncing](./async-debouncing.md) for Promise results and configurable async error handling.
108​
109## Execution timing
110​
111The `leading` and `trailing` options control which edge of the wait period may execute.
112​
113| `leading` | `trailing` | Behavior |
114| --- | --- | --- |
115| `false` | `true` | Wait for inactivity, then execute the most recent call. This is the default. |
116| `true` | `false` | Execute the first call immediately. Later calls do not execute and restart the wait period. |
117| `true` | `true` | Execute the first call immediately. If another call arrives during the wait period, execute the most recent call at the trailing edge. |
118| `false` | `false` | Do not execute any calls. |
119​
120```ts
121const debouncer = new Debouncer(saveDraft, {
122 wait: 1000,
123 leading: true,
124 trailing: true,
125})
126​
127debouncer.maybeExecute('first') // Executes immediately.
128debouncer.maybeExecute('second')
129debouncer.maybeExecute('latest') // Executes after 1 second of inactivity.
130```
131​
132With both edges enabled, a single call executes only on the leading edge. A trailing execution occurs only when another call arrives during the wait period.
133​
134### No maximum wait
135​
136`Debouncer` does not provide a `maxWait` option. A continuous stream of calls can keep postponing a trailing execution indefinitely. Use [throttling](./throttling.md) when work must continue at a bounded interval while calls are still arriving.
137​
138## Controlling pending work
139​
140The class API distinguishes between executing, canceling, and resetting pending work.
141​
142### Flush
143​
144`flush()` immediately executes the pending trailing call with the most recent arguments. It does nothing when no trailing call is pending.
145​
146```ts
147const debouncer = new Debouncer(saveDraft, { wait: 1000 })
148​
149debouncer.maybeExecute('draft')
150debouncer.flush() // Executes saveDraft('draft') now.
151```
152​
153### Cancel
154​
155`cancel()` clears the pending timeout without executing the function. It also allows a leading call to execute immediately the next time `maybeExecute()` is called.
156​
157```ts
158debouncer.maybeExecute('discarded draft')
159debouncer.cancel()
160```
161​
162### Reset
163​
164`reset()` restores the debouncer's state counters and flags to their defaults. It does not clear an already scheduled timeout. Call `cancel()` first when you need to discard pending work and reset state.
165​
166```ts
167debouncer.cancel()
168debouncer.reset()
169```
170​
171## Configuring behavior at runtime
172​
173Use `setOptions()` to change options after construction:
174​
175```ts
176debouncer.setOptions({
177 wait: 1000,
178 leading: true,
179 trailing: false,
180})
181```
182​
183A new `wait` value applies when the next call schedules a timeout. It does not reschedule a timeout that is already pending. Calling `maybeExecute()` again clears the old timeout and schedules a new one using the current options.
184​
185### Enabling and disabling
186​
187Set `enabled` to `false` to prevent execution. Disabling a debouncer through `setOptions()` also cancels its pending call.
188​
189```ts
190const debouncer = new Debouncer(saveDraft, {
191 wait: 500,
192 enabled: false,
193})
194​
195debouncer.maybeExecute('ignored')
196debouncer.setOptions({ enabled: true })
197debouncer.maybeExecute('saved')
198```
199​
200The `enabled` and `wait` options may also be functions that receive the debouncer instance:
201​
202```ts
203const debouncer = new Debouncer(saveDraft, {
204 enabled: (debouncer) => debouncer.store.state.executionCount < 10,
205 wait: (debouncer) =>
206 debouncer.store.state.executionCount === 0 ? 300 : 500,
207})
208```
209​
210### Observing executions
211​
212Use `onExecute` for a side effect after the wrapped function runs. The callback receives the executed arguments followed by the debouncer instance.
213​
214```ts
215const debouncer = new Debouncer(saveDraft, {
216 wait: 500,
217 onExecute: (args, debouncer) => {
218 console.log('Saved arguments:', args)
219 console.log('Execution count:', debouncer.store.state.executionCount)
220 },
221})
222```
223​
224To share a type-checked configuration across instances, define it with `debouncerOptions()`.
225​
226## State
227​
228The class stores its state in a TanStack Store at `debouncer.store`.
229​
230To restore selected state that your app has persisted, pass a partial snapshot through `initialState`. It is merged with the defaults. Restore only durable fields. Pending timers are not restored.
231​
232The properties most commonly used in application code are:
233​
234- `isPending`: Whether a trailing execution is waiting.
235- `executionCount`: How many times the wrapped function has executed.
236- `lastArgs`: The arguments recorded by the most recent trailing-enabled call. Check `isPending` before treating them as pending work.
237- `status`: `'disabled'`, `'idle'`, or `'pending'`.
238​
239```ts
240const unsubscribe = debouncer.store.subscribe((state) => {
241 console.log(state.isPending, state.executionCount)
242})
243​
244unsubscribe()
245```
246​
247See the [`Debouncer` API reference](../../../reference/classes/Debouncer.md) for the complete state and option types.