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

debouncing.md

262 lines10.6 KB

1---
2title: Lit 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 Lit
49​
50The adapter provides two levels of debouncing API:
51​
52- `createDebouncedState` and `createDebouncedValue` delay state or a changing value.
53- `createDebouncer` exposes lifecycle methods, dynamic options, callbacks, and selected state.
54​
55Create utilities as fields or during construction of a Lit element, and pass the element as the first argument. The snippets below belong to that element. Reactive options refresh when its host updates.
56​
57The snippets use application functions such as `saveDraft` and `updateSearchResults`. Supply those functions in your component.
58​
59### Debounced callback
60​
61Use `createDebouncer(...).maybeExecute` when an event should invoke a debounced side effect:
62​
63```ts
64import { createDebouncer } from '@tanstack/lit-pacer'
65​
66// Fields on a LitElement:
67search = createDebouncer(
68 this,
69 (query: string) => updateSearchResults(query),
70 {
71 wait: 500,
72 },
73).maybeExecute
74onInput = (event: Event) => {
75 this.search((event.target as HTMLInputElement).value)
77```
78​
79Keep the utility instance when the component also needs `cancel()` or `flush()`. Its bound `maybeExecute` method can be passed directly as an event handler.
80​
81### Debounced state and values
82​
83Use `createDebouncedState` when Pacer should own the delayed state, or `createDebouncedValue` when a value already changes elsewhere:
84​
85```ts
86import { createDebouncedValue } from '@tanstack/lit-pacer'
87​
88// query is a reactive property on this LitElement.
89delayed = createDebouncedValue(this, () => this.query, { wait: 500 })
90// Read this.delayed[0]() in render().
91```
92​
93### Instance API
94​
95```ts
96import { createDebouncer } from '@tanstack/lit-pacer'
97​
98debouncer = createDebouncer(this, saveDraft, { wait: 500 }, (state) => ({
99 isPending: state.isPending,
100}))
101// In render():
102// html`<button ?disabled=${!this.debouncer.state.isPending}
103// @click=${() => this.debouncer.flush()}>Save now</button>`
104```
105​
106The bound `maybeExecute()` method returns `void`. The synchronous adapter does not retain return values or catch errors. Handle errors inside a trailing callback, or use [async debouncing](./async-debouncing.md) when the caller needs a Promise result.
107​
108The following timing and control snippets use the `debouncer` instance created in your component. Run those operations from event handlers or other application code.
109​
110## Execution timing
111​
112The `leading` and `trailing` options control which edge of the wait period may execute.
113​
114| `leading` | `trailing` | Behavior |
115| --------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------- |
116| `false` | `true` | Wait for inactivity, then execute the most recent call. This is the default. |
117| `true` | `false` | Execute the first call immediately. Later calls do not execute and restart the wait period. |
118| `true` | `true` | Execute the first call immediately. If another call arrives during the wait period, execute the most recent call at the trailing edge. |
119| `false` | `false` | Do not execute any calls. |
120​
121```ts
122debouncer.setOptions({
123 wait: 1000,
124 leading: true,
125 trailing: true,
126})
127​
128debouncer.maybeExecute('first') // Executes immediately.
129debouncer.maybeExecute('second')
130debouncer.maybeExecute('latest') // Executes after 1 second of inactivity.
131```
132​
133With 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.
134​
135### No maximum wait
136​
137`createDebouncer` 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.
138​
139## Controlling pending work
140​
141The instance API distinguishes between executing, canceling, and resetting pending work.
142​
143### Flush
144​
145`flush()` immediately executes the pending trailing call with the most recent arguments. It does nothing when no trailing call is pending.
146​
147```ts
148debouncer.setOptions({ wait: 1000 })
149​
150debouncer.maybeExecute('draft')
151debouncer.flush() // Executes saveDraft('draft') now.
152```
153​
154### Cancel
155​
156`cancel()` clears the pending timeout without executing the function. It also allows a leading call to execute immediately the next time `maybeExecute()` is called.
157​
158```ts
159debouncer.maybeExecute('discarded draft')
160debouncer.cancel()
161```
162​
163### Reset
164​
165`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.
166​
167```ts
168debouncer.cancel()
169debouncer.reset()
170```
171​
172## Configuring behavior at runtime
173​
174Use `setOptions()` to change options after construction:
175​
176```ts
177debouncer.setOptions({
178 wait: 1000,
179 leading: true,
180 trailing: false,
181})
182```
183​
184A 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.
185​
186### Enabling and disabling
187​
188Set `enabled` to `false` to prevent execution. Disabling a debouncer through `setOptions()` also cancels its pending call.
189​
190```ts
191debouncer.setOptions({
192 wait: 500,
193 enabled: false,
194})
195​
196debouncer.maybeExecute('ignored')
197debouncer.setOptions({ enabled: true })
198debouncer.maybeExecute('saved')
199```
200​
201The `enabled` and `wait` options may also be functions that receive the debouncer instance:
202​
203```ts
204debouncer.setOptions({
205 enabled: (debouncer) => debouncer.store.state.executionCount < 10,
206 wait: (debouncer) => (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
215debouncer.setOptions({
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​
224### Reactive options
225​
226Pass an options factory or property getters to read reactive settings. Local options override provider defaults, and option changes retain the same utility instance.
227​
228```ts
229// wait is a reactive property on this LitElement.
230debouncer = createDebouncer(this, saveDraft, () => ({ wait: this.wait }))
231```
232​
233## Lit lifecycle
234​
235Disconnecting the Lit host cancels pending work and unsubscribes from state. Reconnection refreshes options and restores subscriptions to the same utility. Providing `onUnmount` replaces the default cleanup, so a custom callback must perform every required lifecycle action. Flushing during teardown can run callbacks after the component has begun to be destroyed.
236​
237## Reactive state
238​
239Pass a selector to subscribe to the state your component reads. Without a selector, selected state is an empty object. Read the selection through `this.debouncer.state`. The core store remains available even when you do not select state for rendering.
240​
241Option functions and lifecycle callbacks receive the public utility instance. Reading `.store.state` in those callbacks is supported. Component rendering should read the selected adapter state.
242​
243### Child subscriptions
244​
245A child can select state without subscribing the utility owner. The child subscription cleans up when its own scope or component is destroyed:
246​
247```ts
248// In a child LitElement, using a utility supplied by its parent:
249const selected = debouncer.subscribe(this, (state) => ({
250 isPending: state.isPending,
251}))
252// Read selected().isPending in the child's render().
253```
254​
255To 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.
256​
257- `isPending`: Whether a trailing execution is waiting.
258- `executionCount`: How many times the wrapped function has executed.
259- `lastArgs`: The arguments recorded by the most recent trailing-enabled call. Check `isPending` before treating them as pending work.
260- `status`: `'disabled'`, `'idle'`, or `'pending'`.
261​
262See the [Lit API reference](../reference/index.md) for adapter signatures and the [quick start](../quick-start.md) for default options and helper return values.