Open History to see the last commit
1---
2title: Alpine 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 Alpine
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 a Pacer scope for an Alpine component and create utilities from its `init()` method. Call `scope.destroy()` from the component's `destroy()` method. The snippets below assume that `scope` is this component-owned scope.
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
64const search = scope.createDebouncer(
65 (query: string) => updateSearchResults(query),
66 { wait: 500 },
67).maybeExecute
68// In the component's input handler:
69search(this.query)
70```
71
72Keep the utility instance when the component also needs `cancel()` or `flush()`. Its bound `maybeExecute` method can be passed directly as an event handler.
73
74### Debounced state and values
75
76Use `createDebouncedState` when Pacer should own the delayed state, or `createDebouncedValue` when a value already changes elsewhere:
77
78```ts
79const [debouncedQuery] = scope.createDebouncedValue(() => this.query, {
80 wait: 500,
81})
82// Return debouncedQuery from the data object and read debouncedQuery() in x-text.
83```
84
85### Instance API
86
87```ts
88this.debouncer = scope.createDebouncer(saveDraft, { wait: 500 }, (state) => ({
89 isPending: state.isPending,
90}))
91// Use :disabled="!debouncer.state.isPending" and @click="debouncer.flush()".
92```
93
94The 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.
95
96The following timing and control snippets use the `debouncer` instance created in your component. Run those operations from event handlers or other application code.
97
98## Execution timing
99
100The `leading` and `trailing` options control which edge of the wait period may execute.
101
102| `leading` | `trailing` | Behavior |
103| --------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------- |
104| `false` | `true` | Wait for inactivity, then execute the most recent call. This is the default. |
105| `true` | `false` | Execute the first call immediately. Later calls do not execute and restart the wait period. |
106| `true` | `true` | Execute the first call immediately. If another call arrives during the wait period, execute the most recent call at the trailing edge. |
107| `false` | `false` | Do not execute any calls. |
108
109```ts
110debouncer.setOptions({
111 wait: 1000,
112 leading: true,
113 trailing: true,
114})
115
116debouncer.maybeExecute('first') // Executes immediately.
117debouncer.maybeExecute('second')
118debouncer.maybeExecute('latest') // Executes after 1 second of inactivity.
119```
120
121With 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.
122
123### No maximum wait
124
125`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.
126
127## Controlling pending work
128
129The instance API distinguishes between executing, canceling, and resetting pending work.
130
131### Flush
132
133`flush()` immediately executes the pending trailing call with the most recent arguments. It does nothing when no trailing call is pending.
134
135```ts
136debouncer.setOptions({ wait: 1000 })
137
138debouncer.maybeExecute('draft')
139debouncer.flush() // Executes saveDraft('draft') now.
140```
141
142### Cancel
143
144`cancel()` clears the pending timeout without executing the function. It also allows a leading call to execute immediately the next time `maybeExecute()` is called.
145
146```ts
147debouncer.maybeExecute('discarded draft')
148debouncer.cancel()
149```
150
151### Reset
152
153`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.
154
155```ts
156debouncer.cancel()
157debouncer.reset()
158```
159
160## Configuring behavior at runtime
161
162Use `setOptions()` to change options after construction:
163
164```ts
165debouncer.setOptions({
166 wait: 1000,
167 leading: true,
168 trailing: false,
169})
170```
171
172A 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.
173
174### Enabling and disabling
175
176Set `enabled` to `false` to prevent execution. Disabling a debouncer through `setOptions()` also cancels its pending call.
177
178```ts
179debouncer.setOptions({
180 wait: 500,
181 enabled: false,
182})
183
184debouncer.maybeExecute('ignored')
185debouncer.setOptions({ enabled: true })
186debouncer.maybeExecute('saved')
187```
188
189The `enabled` and `wait` options may also be functions that receive the debouncer instance:
190
191```ts
192debouncer.setOptions({
193 enabled: (debouncer) => debouncer.store.state.executionCount < 10,
194 wait: (debouncer) => (debouncer.store.state.executionCount === 0 ? 300 : 500),
195})
196```
197
198### Observing executions
199
200Use `onExecute` for a side effect after the wrapped function runs. The callback receives the executed arguments followed by the debouncer instance.
201
202```ts
203debouncer.setOptions({
204 wait: 500,
205 onExecute: (args, debouncer) => {
206 console.log('Saved arguments:', args)
207 console.log('Execution count:', debouncer.store.state.executionCount)
208 },
209})
210```
211
212### Reactive options
213
214Pass an options factory or property getters to read reactive settings. Local options override provider defaults, and option changes retain the same utility instance.
215
216```ts
217this.debouncer = scope.createDebouncer(saveDraft, () => ({ wait: this.wait }))
218```
219
220## Alpine lifecycle
221
222Destroying the Pacer scope cancels pending work, releases reactive effects, and unsubscribes from state. Connect that cleanup to Alpine's `destroy()` method. 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.
223
224## Reactive state
225
226Pass a selector to subscribe to the state your component reads. Without a selector, selected state is an empty object. Read the selection through `debouncer.state`. The core store remains available even when you do not select state for rendering.
227
228Option 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.
229
230### Child subscriptions
231
232A child can select state without subscribing the utility owner. The child subscription cleans up when its own scope or component is destroyed:
233
234```ts
235const selected = debouncer.subscribe(childScope, (state) => ({
236 isPending: state.isPending,
237}))
238// Read selected().isPending in the child component.
239// childScope.destroy() removes this subscription without canceling the parent utility.
240```
241
242To 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.
243
244- `isPending`: Whether a trailing execution is waiting.
245- `executionCount`: How many times the wrapped function has executed.
246- `lastArgs`: The arguments recorded by the most recent trailing-enabled call. Check `isPending` before treating them as pending work.
247- `status`: `'disabled'`, `'idle'`, or `'pending'`.
248
249See the [Alpine API reference](../reference/index.md) for adapter signatures and the [quick start](../quick-start.md) for default options and helper return values.