Open History to see the last commit
1---
2title: Alpine Queuing Guide
3id: queuing
4---
5
6Queuing stores operations in an ordered buffer and processes them individually. It is the primary Pacer strategy for work that should not be discarded when calls arrive faster than they can run.
7
8Queues are lossless only while they have capacity. A finite `maxSize`, explicit clearing, expiration, or a processing error can still remove or reject work.
9
10## How queuing works
11
12```text
13Queuing (process one item every 2 ticks)
14Timeline: [1 second per tick]
15Calls: ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️
16Queue: [ABC] [BC] [BCDE] [DE] [E] []
17Executed: ✅ ✅ ✅ ✅ ✅ ✅
18 [======================================================]
19 ^ Accepted items remain queued until processed
20
21 [Items arrive] [Process steadily] [Empty]
22```
23
24The queue can process automatically with a delay between items, or remain stopped for manual processing.
25
26## When to use queuing
27
28Choose queuing when:
29
30- Every accepted operation should run individually.
31- Processing order matters.
32- Incoming work may temporarily exceed processing capacity.
33- A maximum buffer size should reject excess work explicitly.
34- FIFO, LIFO, or priority ordering is required.
35
36Choose another utility when:
37
38- Only the final call matters. Use [debouncing](./debouncing.md).
39- Intermediate calls may be discarded while work runs steadily. Use [throttling](./throttling.md).
40- Calls should be rejected after a time-window quota. Use [rate limiting](./rate-limiting.md).
41- Items should run together. Use [batching](./batching.md).
42- Tasks return Promises or should run concurrently. Use [async queuing](./async-queuing.md).
43
44## Choose an API
45
46- `createQueuedState` or `createQueuedValue` for a queue connected to Alpine state
47- `createQueuer` for direct queue lifecycle and ordering control
48
49Use the queued state or value API when queue contents drive the UI. Use the instance API for ordering, capacity, expiration, pause, resume, flush, and manual processing.
50
51## Alpine example
52
53Create one Pacer scope for each Alpine component and destroy it from the component's `destroy` method. The example imports application operations from `./api`.
54
55```ts
56import Alpine from 'alpinejs'
57import { createPacerScope } from '@tanstack/alpine-pacer'
58import { processJob } from './api'
59
60Alpine.data('example', () => {
61 const scope = createPacerScope()
62 const queue = scope.createQueuer(processJob, { wait: 500 }, (state) => ({
63 items: state.items,
64 isRunning: state.isRunning,
65 }))
66 return {
67 queue,
68 schedule() {
69 void queue.addItem('task')
70 },
71 destroy() {
72 scope.destroy()
73 },
74 }
75})
76
77Alpine.start()
78```
79
80```html
81<div x-data="example">
82 <button @click="schedule">Add job</button>
83 <output x-text="queue.state.items.length"></output>
84</div>
85```
86
87The focused snippets below use the component-owned `scope` created above. Call their control methods from event handlers.
88
89Pass `initialItems` when work is already available at creation time. The queue applies its normal insertion and capacity rules, and automatic processing can begin immediately unless `started: false` is set.
90
91`createQueuedState` returns `[itemsAccessor, addItem, queue]`. Call `itemsAccessor()` to read pending items.
92
93## Ordering items
94
95Automatic processing uses `addItemsTo` to choose where new items enter and `getItemsFrom` to choose where items leave.
96
97### FIFO
98
99FIFO processes the oldest item first. This is the default.
100
101```ts
102const queuer = scope.createQueuer(processItem, {
103 addItemsTo: 'back',
104 getItemsFrom: 'front',
105 started: false,
106})
107
108queuer.addItem(1)
109queuer.addItem(2)
110queuer.addItem(3)
111queuer.start() // Processes 1, 2, 3.
112```
113
114### LIFO
115
116LIFO processes the newest item first.
117
118```ts
119const queuer = scope.createQueuer(processItem, {
120 addItemsTo: 'back',
121 getItemsFrom: 'back',
122 started: false,
123})
124
125queuer.addItem(1)
126queuer.addItem(2)
127queuer.addItem(3)
128queuer.start() // Processes 3, 2, 1.
129```
130
131### Priority
132
133Provide `getPriority` to process higher numeric priorities first. Priority ordering takes precedence over front and back retrieval.
134
135```ts
136type Task = { name: string; priority: number }
137
138const queuer = createQueuer<Task>(processTask, {
139 getPriority: (task) => task.priority,
140 started: false,
141})
142
143queuer.addItem({ name: 'low', priority: 1 })
144queuer.addItem({ name: 'high', priority: 3 })
145queuer.addItem({ name: 'medium', priority: 2 })
146queuer.start() // Processes high, medium, low.
147```
148
149## Automatic and manual processing
150
151Queues start automatically by default. The first accepted item processes immediately, then `wait` controls the delay before later items.
152
153```ts
154const queuer = scope.createQueuer(processItem, {
155 wait: 1000,
156})
157```
158
159Set `started: false` to collect items before processing:
160
161```ts
162const queuer = scope.createQueuer(processItem, { started: false })
163
164queuer.addItem(1)
165queuer.addItem(2)
166queuer.start()
167queuer.stop()
168```
169
170`stop()` cancels the scheduled tick and retains queued items. `start()` resumes automatic processing.
171
172For manual control:
173
174- `execute()` removes and processes the next item immediately.
175- `getNextItem()` removes and returns the next item without processing it.
176- `peekNextItem()` returns the next item without removing it.
177- `peekAllItems()` returns a copy of the current queue.
178
179## Capacity and rejection
180
181Set `maxSize` to bound the number of waiting items. An item added to a full queue is rejected, `addItem()` returns `false`, and `onReject` runs.
182
183```ts
184const queuer = scope.createQueuer(processItem, {
185 maxSize: 2,
186 started: false,
187 onReject: (item, queuer) => {
188 console.log('Rejected:', item)
189 console.log('Total rejections:', queuer.store.state.rejectionCount)
190 },
191})
192
193queuer.addItem(1) // true
194queuer.addItem(2) // true
195queuer.addItem(3) // false
196```
197
198The active synchronous execution is not part of `size`; `size` counts items still waiting in the queue.
199
200## Expiring stale items
201
202Use `expirationDuration` to remove items that have waited too long:
203
204```ts
205const queuer = scope.createQueuer(processItem, {
206 expirationDuration: 5000,
207 onExpire: (item) => {
208 console.log('Expired:', item)
209 },
210})
211```
212
213Use `getIsExpired` for custom logic:
214
215```ts
216const queuer = scope.createQueuer(processItem, {
217 getIsExpired: (item, addedAt) => Date.now() - addedAt > item.maxAge,
218})
219```
220
221Expiration is checked while the automatic processing loop runs. A stopped queue evaluates stale items when processing resumes.
222
223## Flushing, clearing, and resetting
224
225### Flush
226
227`flush()` processes waiting items immediately without the configured delay. Pass a count to process only part of the queue.
228
229```ts
230queuer.flush() // Process all waiting items.
231queuer.flush(2) // Process at most two waiting items.
232```
233
234`flushAsBatch()` removes all waiting items and passes them to a separate batch function:
235
236```ts
237queuer.flushAsBatch((items) => {
238 saveItems(items)
239})
240```
241
242### Clear
243
244`clear()` removes all waiting items without processing them. It does not change whether the queue is running.
245
246```ts
247queuer.clear()
248```
249
250### Reset
251
252`reset()` restores state to the default running, empty queue. It does not clear an already scheduled timeout. Call `stop()` before `reset()` when scheduled work must be canceled.
253
254```ts
255queuer.stop()
256queuer.reset()
257```
258
259## Configuring and observing the queue
260
261Use `setOptions()` to update future behavior. Changing `started` through `setOptions()` does not call `start()` or `stop()`.
262
263```ts
264queuer.setOptions({ wait: 250, maxSize: 20 })
265queuer.start()
266```
267
268The `wait` option may be a function that receives the queuer instance:
269
270```ts
271const queuer = scope.createQueuer(processItem, {
272 wait: (queuer) => (queuer.store.state.size > 20 ? 50 : 250),
273})
274```
275
276Use callbacks for queue events:
277
278- `onItemsChange`: An item was added or removed.
279- `onExecute`: An item was processed.
280- `onReject`: An item was rejected.
281- `onExpire`: An item expired.
282
283## Alpine lifecycle
284
285The adapter stops automatic processing when its owner is destroyed. Providing `onUnmount` replaces that default cleanup, so a custom callback must perform every required lifecycle action. When custom cleanup flushes work, remember that user callbacks can run while the component is being destroyed.
286
287## Reactive state
288
289The adapter subscribes only to the state returned by the selector argument. Without a selector, the adapter state is empty. Create the utility in its owning scope and select fields used by `x-text` and `x-bind`:
290
291```ts
292const queuer = scope.createQueuer(processItem, { wait: 250 }, (state) => ({
293 size: state.size,
294 isRunning: state.isRunning,
295}))
296
297console.log(queuer.state.size, queuer.state.isRunning)
298```
299
300Use `utility.subscribe(childScope, selector)` for an independently subscribed child scope. It returns a selected-state getter and cleans up with that child scope.
301
302Option functions and lifecycle callbacks receive the underlying public utility instance. The `.store.state` reads inside those callbacks in the examples above are supported. Rendering code should read the selected adapter state shown here.
303
304`initialState` can restore selected queue state that your app has persisted. If it includes `items`, they take precedence over `initialItems`; `initialState.isRunning` likewise takes precedence over `started`. Restore only durable fields. Pending timers are not restored.
305
306Commonly useful state includes:
307
308- `items` and `size`: Items still waiting.
309- `isRunning`: Whether automatic processing is enabled.
310- `isIdle`: Whether a running queue is empty.
311- `isFull`: Whether `maxSize` has been reached.
312- `executionCount`: Items whose wrapped function returned successfully.
313- `rejectionCount` and `expirationCount`: Items removed without processing.
314- `status`: `'idle'`, `'running'`, or `'stopped'`.
315
316See the [Alpine API reference](../reference/index.md) for adapter signatures and the public core reference for complete option and state types.