@tanstack/pacer 0.21.1 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +21 -6
  2. package/dist/async-batcher.d.ts +11 -14
  3. package/dist/async-batcher.js +186 -132
  4. package/dist/async-debouncer.d.ts +10 -13
  5. package/dist/async-debouncer.js +187 -146
  6. package/dist/async-queuer.d.ts +12 -14
  7. package/dist/async-queuer.js +384 -259
  8. package/dist/async-rate-limiter.d.ts +9 -12
  9. package/dist/async-rate-limiter.js +198 -147
  10. package/dist/async-retryer.d.ts +10 -10
  11. package/dist/async-retryer.js +209 -188
  12. package/dist/async-throttler.d.ts +10 -13
  13. package/dist/async-throttler.js +215 -161
  14. package/dist/batcher.d.ts +5 -8
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -9
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -11
  19. package/dist/event-client.js +1 -2
  20. package/dist/index.js +1 -1
  21. package/dist/queuer.d.ts +8 -10
  22. package/dist/queuer.js +277 -207
  23. package/dist/rate-limiter.d.ts +6 -9
  24. package/dist/rate-limiter.js +127 -109
  25. package/dist/throttler.d.ts +6 -9
  26. package/dist/throttler.js +127 -90
  27. package/dist/types.d.ts +4 -6
  28. package/dist/utils.d.ts +3 -6
  29. package/dist/utils.js +1 -2
  30. package/package.json +23 -70
  31. package/dist/async-batcher.cjs +0 -337
  32. package/dist/async-batcher.cjs.map +0 -1
  33. package/dist/async-batcher.d.cts +0 -344
  34. package/dist/async-batcher.js.map +0 -1
  35. package/dist/async-debouncer.cjs +0 -330
  36. package/dist/async-debouncer.cjs.map +0 -1
  37. package/dist/async-debouncer.d.cts +0 -300
  38. package/dist/async-debouncer.js.map +0 -1
  39. package/dist/async-queuer.cjs +0 -484
  40. package/dist/async-queuer.cjs.map +0 -1
  41. package/dist/async-queuer.d.cts +0 -440
  42. package/dist/async-queuer.js.map +0 -1
  43. package/dist/async-rate-limiter.cjs +0 -373
  44. package/dist/async-rate-limiter.cjs.map +0 -1
  45. package/dist/async-rate-limiter.d.cts +0 -357
  46. package/dist/async-rate-limiter.js.map +0 -1
  47. package/dist/async-retryer.cjs +0 -374
  48. package/dist/async-retryer.cjs.map +0 -1
  49. package/dist/async-retryer.d.cts +0 -319
  50. package/dist/async-retryer.js.map +0 -1
  51. package/dist/async-throttler.cjs +0 -347
  52. package/dist/async-throttler.cjs.map +0 -1
  53. package/dist/async-throttler.d.cts +0 -320
  54. package/dist/async-throttler.js.map +0 -1
  55. package/dist/batcher.cjs +0 -200
  56. package/dist/batcher.cjs.map +0 -1
  57. package/dist/batcher.d.cts +0 -180
  58. package/dist/batcher.js.map +0 -1
  59. package/dist/debouncer.cjs +0 -203
  60. package/dist/debouncer.cjs.map +0 -1
  61. package/dist/debouncer.d.cts +0 -167
  62. package/dist/debouncer.js.map +0 -1
  63. package/dist/event-client.cjs +0 -64
  64. package/dist/event-client.cjs.map +0 -1
  65. package/dist/event-client.d.cts +0 -66
  66. package/dist/event-client.js.map +0 -1
  67. package/dist/index.cjs +0 -52
  68. package/dist/index.d.cts +0 -15
  69. package/dist/queuer.cjs +0 -401
  70. package/dist/queuer.cjs.map +0 -1
  71. package/dist/queuer.d.cts +0 -345
  72. package/dist/queuer.js.map +0 -1
  73. package/dist/rate-limiter.cjs +0 -263
  74. package/dist/rate-limiter.cjs.map +0 -1
  75. package/dist/rate-limiter.d.cts +0 -215
  76. package/dist/rate-limiter.js.map +0 -1
  77. package/dist/throttler.cjs +0 -215
  78. package/dist/throttler.cjs.map +0 -1
  79. package/dist/throttler.d.cts +0 -207
  80. package/dist/throttler.js.map +0 -1
  81. package/dist/types.cjs +0 -0
  82. package/dist/types.d.cts +0 -13
  83. package/dist/utils.cjs +0 -14
  84. package/dist/utils.cjs.map +0 -1
  85. package/dist/utils.d.cts +0 -8
  86. package/dist/utils.js.map +0 -1
  87. package/src/async-batcher.ts +0 -594
  88. package/src/async-debouncer.ts +0 -565
  89. package/src/async-queuer.ts +0 -925
  90. package/src/async-rate-limiter.ts +0 -647
  91. package/src/async-retryer.ts +0 -684
  92. package/src/async-throttler.ts +0 -633
  93. package/src/batcher.ts +0 -329
  94. package/src/debouncer.ts +0 -334
  95. package/src/event-client.ts +0 -129
  96. package/src/index.ts +0 -24
  97. package/src/queuer.ts +0 -740
  98. package/src/rate-limiter.ts +0 -429
  99. package/src/throttler.ts +0 -380
  100. package/src/types.ts +0 -12
  101. package/src/utils.ts +0 -12
@@ -1,565 +0,0 @@
1
- import { Store } from '@tanstack/store'
2
- import { AsyncRetryer } from './async-retryer'
3
- import { parseFunctionOrValue } from './utils'
4
- import { emitChange, pacerEventClient } from './event-client'
5
- import type { AsyncRetryerOptions } from './async-retryer'
6
- import type { AnyAsyncFunction, OptionalKeys } from './types'
7
-
8
- export interface AsyncDebouncerState<TFn extends AnyAsyncFunction> {
9
- /**
10
- * Whether the debouncer can execute on the leading edge of the timeout
11
- */
12
- canLeadingExecute: boolean
13
- /**
14
- * Number of function executions that have resulted in errors
15
- */
16
- errorCount: number
17
- /**
18
- * Whether the debounced function is currently executing asynchronously
19
- */
20
- isExecuting: boolean
21
- /**
22
- * Whether the debouncer is waiting for the timeout to trigger execution
23
- */
24
- isPending: boolean
25
- /**
26
- * The arguments from the most recent call to maybeExecute
27
- */
28
- lastArgs: Parameters<TFn> | undefined
29
- /**
30
- * The result from the most recent successful function execution
31
- */
32
- lastResult: ReturnType<TFn> | undefined
33
- /**
34
- * Number of times maybeExecute has been called (for reduction calculations)
35
- */
36
- maybeExecuteCount: number
37
- /**
38
- * Number of function executions that have completed (either successfully or with errors)
39
- */
40
- settleCount: number
41
- /**
42
- * Current execution status - 'idle' when not active, 'pending' when waiting, 'executing' when running, 'settled' when completed
43
- */
44
- status: 'disabled' | 'idle' | 'pending' | 'executing' | 'settled'
45
- /**
46
- * Number of function executions that have completed successfully
47
- */
48
- successCount: number
49
- }
50
-
51
- function getDefaultAsyncDebouncerState<
52
- TFn extends AnyAsyncFunction,
53
- >(): AsyncDebouncerState<TFn> {
54
- return {
55
- canLeadingExecute: true,
56
- errorCount: 0,
57
- isExecuting: false,
58
- isPending: false,
59
- lastArgs: undefined,
60
- lastResult: undefined,
61
- maybeExecuteCount: 0,
62
- settleCount: 0,
63
- status: 'idle',
64
- successCount: 0,
65
- }
66
- }
67
-
68
- /**
69
- * Options for configuring an async debounced function
70
- */
71
- export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
72
- /**
73
- * Options for configuring the underlying async retryer
74
- */
75
- asyncRetryerOptions?: AsyncRetryerOptions<TFn>
76
- /**
77
- * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
78
- * Can be a boolean or a function that returns a boolean.
79
- * Defaults to true.
80
- */
81
- enabled?: boolean | ((debouncer: AsyncDebouncer<TFn>) => boolean)
82
- /**
83
- * Initial state for the async debouncer
84
- */
85
- initialState?: Partial<AsyncDebouncerState<TFn>>
86
- /**
87
- * Optional key to identify this async debouncer instance.
88
- * If provided, the async debouncer will be identified by this key in the devtools and PacerProvider if applicable.
89
- */
90
- key?: string
91
- /**
92
- * Whether to execute on the leading edge of the timeout.
93
- * Defaults to false.
94
- */
95
- leading?: boolean
96
- /**
97
- * Optional error handler for when the debounced function throws.
98
- * If provided, the handler will be called with the error and debouncer instance.
99
- * This can be used alongside throwOnError - the handler will be called before any error is thrown.
100
- */
101
- onError?: (
102
- error: Error,
103
- args: Parameters<TFn>,
104
- debouncer: AsyncDebouncer<TFn>,
105
- ) => void
106
- /**
107
- * Optional callback to call when the debounced function is executed
108
- */
109
- onSettled?: (args: Parameters<TFn>, debouncer: AsyncDebouncer<TFn>) => void
110
- /**
111
- * Optional callback to call when the debounced function is executed
112
- */
113
- onSuccess?: (
114
- result: ReturnType<TFn>,
115
- args: Parameters<TFn>,
116
- debouncer: AsyncDebouncer<TFn>,
117
- ) => void
118
- /**
119
- * Whether to throw errors when they occur.
120
- * Defaults to true if no onError handler is provided, false if an onError handler is provided.
121
- * Can be explicitly set to override these defaults.
122
- */
123
- throwOnError?: boolean
124
- /**
125
- * Whether to execute on the trailing edge of the timeout.
126
- * Defaults to true.
127
- */
128
- trailing?: boolean
129
- /**
130
- * Delay in milliseconds to wait after the last call before executing.
131
- * Can be a number or a function that returns a number.
132
- * Defaults to 0ms
133
- */
134
- wait: number | ((debouncer: AsyncDebouncer<TFn>) => number)
135
- }
136
-
137
- /**
138
- * Utility function for sharing common `AsyncDebouncerOptions` options between different `AsyncDebouncer` instances.
139
- */
140
- export function asyncDebouncerOptions<
141
- TFn extends AnyAsyncFunction = AnyAsyncFunction,
142
- TOptions extends Partial<AsyncDebouncerOptions<TFn>> = Partial<
143
- AsyncDebouncerOptions<TFn>
144
- >,
145
- >(options: TOptions): TOptions {
146
- return options
147
- }
148
-
149
- type AsyncDebouncerOptionsWithOptionalCallbacks = OptionalKeys<
150
- AsyncDebouncerOptions<any>,
151
- 'initialState' | 'onError' | 'onSettled' | 'onSuccess' | 'key'
152
- >
153
-
154
- const defaultOptions: AsyncDebouncerOptionsWithOptionalCallbacks = {
155
- asyncRetryerOptions: {
156
- maxAttempts: 1,
157
- },
158
- enabled: true,
159
- leading: false,
160
- trailing: true,
161
- wait: 0,
162
- }
163
-
164
- /**
165
- * A class that creates an async debounced function.
166
- *
167
- * Async vs Sync Versions:
168
- * The async version provides advanced features over the sync Debouncer:
169
- * - Returns promises that can be awaited for debounced function results
170
- * - Built-in retry support via AsyncRetryer integration
171
- * - Abort support to cancel in-flight executions
172
- * - Cancel support to prevent pending executions from starting
173
- * - Comprehensive error handling with onError callbacks and throwOnError control
174
- * - Detailed execution tracking (success/error/settle counts)
175
- *
176
- * The sync Debouncer is lighter weight and simpler when you don't need async features,
177
- * return values, or execution control.
178
- *
179
- * What is Debouncing?
180
- * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
181
- * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
182
- * or input changes where you only want to execute the handler after the events have stopped occurring.
183
- *
184
- * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
185
- * the function stops being called for the specified delay period.
186
- *
187
- * Error Handling:
188
- * - If an `onError` handler is provided, it will be called with the error and debouncer instance
189
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
190
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
191
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
192
- * - The error state can be checked using the underlying store
193
- *
194
- * State Management:
195
- * - The debouncer uses a reactive store for state management
196
- * - Use `initialState` to provide initial state values when creating the async debouncer
197
- * - The state includes canLeadingExecute, error count, execution status, and success/settle counts
198
- * - State can be accessed via the `store` property and its `state` getter
199
- * - The store is reactive and will notify subscribers of state changes
200
- *
201
- * @example
202
- * ```ts
203
- * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
204
- * const results = await searchAPI(value);
205
- * return results; // Return value is preserved
206
- * }, {
207
- * wait: 500,
208
- * onError: (error) => {
209
- * console.error('Search failed:', error);
210
- * }
211
- * });
212
- *
213
- * // Called on each keystroke but only executes after 500ms of no typing
214
- * // Returns the API response directly
215
- * const results = await asyncDebouncer.maybeExecute(inputElement.value);
216
- * ```
217
- */
218
- export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
219
- readonly store: Store<Readonly<AsyncDebouncerState<TFn>>> = new Store<
220
- AsyncDebouncerState<TFn>
221
- >(getDefaultAsyncDebouncerState<TFn>())
222
- key: string | undefined
223
- options: AsyncDebouncerOptions<TFn>
224
- asyncRetryers = new Map<number, AsyncRetryer<TFn>>()
225
- #timeoutId: ReturnType<typeof setTimeout> | null = null
226
- #resolvePreviousPromise:
227
- | ((value?: ReturnType<TFn> | undefined) => void)
228
- | null = null
229
-
230
- constructor(
231
- public fn: TFn,
232
- initialOptions: AsyncDebouncerOptions<TFn>,
233
- ) {
234
- this.key = initialOptions.key
235
- this.options = {
236
- ...defaultOptions,
237
- ...initialOptions,
238
- throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,
239
- }
240
- this.#setState(this.options.initialState ?? {})
241
-
242
- if (this.key) {
243
- pacerEventClient.on('d-AsyncDebouncer', (event) => {
244
- if (event.payload.key !== this.key) return
245
- this.#setState(
246
- event.payload.store.state as Partial<AsyncDebouncerState<TFn>>,
247
- )
248
- this.setOptions(
249
- event.payload.options as Partial<AsyncDebouncerOptions<TFn>>,
250
- )
251
- })
252
- }
253
- }
254
-
255
- /**
256
- * Updates the async debouncer options
257
- */
258
- setOptions = (newOptions: Partial<AsyncDebouncerOptions<TFn>>): void => {
259
- this.options = { ...this.options, ...newOptions }
260
-
261
- // Cancel pending execution if the debouncer is disabled
262
- if (!this.#getEnabled()) {
263
- this.cancel()
264
- }
265
- }
266
-
267
- #setState = (newState: Partial<AsyncDebouncerState<TFn>>): void => {
268
- this.store.setState((state) => {
269
- const combinedState = {
270
- ...state,
271
- ...newState,
272
- }
273
- const { isPending, isExecuting, settleCount } = combinedState
274
- return {
275
- ...combinedState,
276
- status: !this.#getEnabled()
277
- ? 'disabled'
278
- : isPending
279
- ? 'pending'
280
- : isExecuting
281
- ? 'executing'
282
- : settleCount > 0
283
- ? 'settled'
284
- : 'idle',
285
- }
286
- })
287
- emitChange('AsyncDebouncer', this)
288
- }
289
-
290
- /**
291
- * Returns the current debouncer enabled state
292
- */
293
- #getEnabled = (): boolean => {
294
- return !!parseFunctionOrValue(this.options.enabled, this)
295
- }
296
-
297
- /**
298
- * Returns the current debouncer wait state
299
- */
300
- #getWait = (): number => {
301
- return parseFunctionOrValue(this.options.wait, this)
302
- }
303
-
304
- /**
305
- * Attempts to execute the debounced function.
306
- * If a call is already in progress, it will be queued.
307
- *
308
- * Error Handling:
309
- * - If the debounced function throws and no `onError` handler is configured,
310
- * the error will be thrown from this method.
311
- * - If an `onError` handler is configured, errors will be caught and passed to the handler,
312
- * and this method will return undefined.
313
- * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
314
- *
315
- * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
316
- * @throws The error from the debounced function if no onError handler is configured
317
- */
318
- maybeExecute = async (
319
- ...args: Parameters<TFn>
320
- ): Promise<ReturnType<TFn> | undefined> => {
321
- if (!this.#getEnabled()) return undefined
322
- this.#cancelPendingExecution()
323
- this.#setState({
324
- lastArgs: args,
325
- maybeExecuteCount: this.store.state.maybeExecuteCount + 1,
326
- })
327
-
328
- // Handle leading execution
329
- if (this.options.leading && this.store.state.canLeadingExecute) {
330
- this.#setState({ canLeadingExecute: false })
331
- await this.#execute(...args)
332
- return this.store.state.lastResult
333
- }
334
-
335
- // Handle trailing execution
336
- if (this.options.trailing && this.#getEnabled()) {
337
- this.#setState({ isPending: true })
338
- }
339
-
340
- return new Promise((resolve, reject) => {
341
- this.#resolvePreviousPromise = resolve
342
- // this.#rejectPreviousPromise = reject
343
- this.#timeoutId = setTimeout(async () => {
344
- // Execute trailing if enabled
345
- if (this.options.trailing && this.store.state.lastArgs) {
346
- try {
347
- await this.#execute(...this.store.state.lastArgs)
348
- } catch (error) {
349
- reject(error)
350
- }
351
- }
352
-
353
- // Reset state and resolve
354
- this.#setState({ canLeadingExecute: true })
355
- this.#resolvePreviousPromise = null
356
- resolve(this.store.state.lastResult)
357
- }, this.#getWait())
358
- })
359
- }
360
-
361
- #execute = async (
362
- ...args: Parameters<TFn>
363
- ): Promise<ReturnType<TFn> | undefined> => {
364
- if (!this.#getEnabled()) return undefined
365
- const currentMaybeExecuteCount = this.store.state.maybeExecuteCount + 1
366
-
367
- try {
368
- this.#setState({ isExecuting: true })
369
- const currentAsyncRetryer = new AsyncRetryer(this.fn, {
370
- ...this.options.asyncRetryerOptions,
371
- key: `${this.key}-retryer-${currentMaybeExecuteCount}`,
372
- })
373
- this.asyncRetryers.set(currentMaybeExecuteCount, currentAsyncRetryer)
374
- const result = await currentAsyncRetryer.execute(...args) // EXECUTE!
375
- this.#setState({
376
- lastResult: result,
377
- successCount: this.store.state.successCount + 1,
378
- })
379
- this.options.onSuccess?.(result as ReturnType<TFn>, args, this)
380
- } catch (error) {
381
- this.#setState({
382
- errorCount: this.store.state.errorCount + 1,
383
- })
384
- this.options.onError?.(error as Error, args, this)
385
- if (this.options.throwOnError) {
386
- throw error
387
- }
388
- } finally {
389
- this.asyncRetryers.delete(currentMaybeExecuteCount) // dispose retryer
390
- this.#setState({
391
- isExecuting: false,
392
- isPending: false,
393
- lastArgs: undefined,
394
- settleCount: this.store.state.settleCount + 1,
395
- })
396
- this.options.onSettled?.(args, this)
397
- }
398
- return this.store.state.lastResult
399
- }
400
-
401
- /**
402
- * Processes the current pending execution immediately
403
- */
404
- flush = async (): Promise<ReturnType<TFn> | undefined> => {
405
- if (this.store.state.isPending && this.store.state.lastArgs) {
406
- const { lastArgs } = this.store.state
407
- this.#cancelPendingExecution()
408
- return await this.#execute(...lastArgs)
409
- }
410
- return undefined
411
- }
412
-
413
- #resolvePreviousPromiseInternal = (): void => {
414
- if (this.#resolvePreviousPromise) {
415
- this.#resolvePreviousPromise(this.store.state.lastResult)
416
- this.#resolvePreviousPromise = null
417
- }
418
- }
419
-
420
- #clearTimeout = (): void => {
421
- if (this.#timeoutId) {
422
- clearTimeout(this.#timeoutId)
423
- this.#timeoutId = null
424
- }
425
- }
426
-
427
- /**
428
- * Internal cancel without resetting the leading execute state
429
- */
430
- #cancelPendingExecution = (): void => {
431
- this.#clearTimeout()
432
- this.#resolvePreviousPromiseInternal()
433
- this.#setState({
434
- isPending: false,
435
- lastArgs: undefined,
436
- })
437
- }
438
-
439
- /**
440
- * Returns the AbortSignal for a specific execution.
441
- * If no maybeExecuteCount is provided, returns the signal for the most recent execution.
442
- * Returns null if no execution is found or not currently executing.
443
- *
444
- * @param maybeExecuteCount - Optional specific execution to get signal for
445
- * @example
446
- * ```typescript
447
- * const debouncer = new AsyncDebouncer(
448
- * async (searchTerm: string) => {
449
- * const signal = debouncer.getAbortSignal()
450
- * if (signal) {
451
- * const response = await fetch(`/api/search?q=${searchTerm}`, { signal })
452
- * return response.json()
453
- * }
454
- * },
455
- * { wait: 300 }
456
- * )
457
- * ```
458
- */
459
- getAbortSignal = (maybeExecuteCount?: number): AbortSignal | null => {
460
- const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount
461
- const retryer = this.asyncRetryers.get(count)
462
- return retryer?.getAbortSignal() ?? null
463
- }
464
-
465
- /**
466
- * Aborts all ongoing executions with the internal abort controllers.
467
- * Does NOT cancel any pending execution that have not started yet.
468
- */
469
- abort = (): void => {
470
- this.asyncRetryers.forEach((retryer) => retryer.abort())
471
- this.asyncRetryers.clear()
472
- this.#setState({
473
- isExecuting: false,
474
- })
475
- }
476
-
477
- /**
478
- * Cancels any pending execution that have not started yet.
479
- * Does NOT abort any execution already in progress.
480
- */
481
- cancel = (): void => {
482
- this.#cancelPendingExecution()
483
- this.#setState({ canLeadingExecute: true })
484
- }
485
-
486
- /**
487
- * Resets the debouncer state to its default values
488
- */
489
- reset = (): void => {
490
- this.#setState(getDefaultAsyncDebouncerState<TFn>())
491
- this.asyncRetryers.forEach((retryer) => retryer.reset())
492
- }
493
- }
494
-
495
- /**
496
- * Creates an async debounced function that delays execution until after a specified wait time.
497
- * The debounced function will only execute once the wait period has elapsed without any new calls.
498
- * If called again during the wait period, the timer resets and a new wait period begins.
499
- *
500
- * Async vs Sync Versions:
501
- * The async version provides advanced features over the sync debounce function:
502
- * - Returns promises that can be awaited for debounced function results
503
- * - Built-in retry support via AsyncRetryer integration
504
- * - Abort support to cancel in-flight executions
505
- * - Cancel support to prevent pending executions from starting
506
- * - Comprehensive error handling with onError callbacks and throwOnError control
507
- * - Detailed execution tracking (success/error/settle counts)
508
- *
509
- * The sync debounce function is lighter weight and simpler when you don't need async features,
510
- * return values, or execution control.
511
- *
512
- * What is Debouncing?
513
- * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
514
- * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
515
- * or input changes where you only want to execute the handler after the events have stopped occurring.
516
- *
517
- * Configuration Options:
518
- * - `wait`: Delay in milliseconds to wait after the last call (required)
519
- * - `leading`: Execute on the leading edge of the timeout (default: false)
520
- * - `trailing`: Execute on the trailing edge of the timeout (default: true)
521
- * - `enabled`: Whether the debouncer is enabled (default: true)
522
- * - `asyncRetryerOptions`: Configure retry behavior for executions
523
- *
524
- * Error Handling:
525
- * - If an `onError` handler is provided, it will be called with the error and debouncer instance
526
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
527
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
528
- * - The error state can be checked using the underlying AsyncDebouncer instance
529
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
530
- *
531
- * State Management:
532
- * - Uses TanStack Store for reactive state management
533
- * - Use `initialState` to provide initial state values when creating the async debouncer
534
- * - Use `onSuccess` callback to react to successful function execution and implement custom logic
535
- * - Use `onError` callback to react to function execution errors and implement custom error handling
536
- * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
537
- * - The state includes canLeadingExecute, error count, execution status, and success/settle counts
538
- * - State can be accessed via `asyncDebouncer.store.state` when using the class directly
539
- * - When using framework adapters (React/Solid), state is accessed from `asyncDebouncer.state`
540
- *
541
- * @example
542
- * ```ts
543
- * const debounced = asyncDebounce(async (value: string) => {
544
- * const result = await saveToAPI(value);
545
- * return result; // Return value is preserved
546
- * }, {
547
- * wait: 1000,
548
- * onError: (error) => {
549
- * console.error('API call failed:', error);
550
- * },
551
- * throwOnError: true // Will both log the error and throw it
552
- * });
553
- *
554
- * // Will only execute once, 1 second after the last call
555
- * // Returns the API response directly
556
- * const result = await debounced("third");
557
- * ```
558
- */
559
- export function asyncDebounce<TFn extends AnyAsyncFunction>(
560
- fn: TFn,
561
- initialOptions: AsyncDebouncerOptions<TFn>,
562
- ) {
563
- const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)
564
- return asyncDebouncer.maybeExecute
565
- }