@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.
- package/README.md +21 -6
- package/dist/async-batcher.d.ts +11 -14
- package/dist/async-batcher.js +186 -132
- package/dist/async-debouncer.d.ts +10 -13
- package/dist/async-debouncer.js +187 -146
- package/dist/async-queuer.d.ts +12 -14
- package/dist/async-queuer.js +384 -259
- package/dist/async-rate-limiter.d.ts +9 -12
- package/dist/async-rate-limiter.js +198 -147
- package/dist/async-retryer.d.ts +10 -10
- package/dist/async-retryer.js +209 -188
- package/dist/async-throttler.d.ts +10 -13
- package/dist/async-throttler.js +215 -161
- package/dist/batcher.d.ts +5 -8
- package/dist/batcher.js +107 -87
- package/dist/debouncer.d.ts +6 -9
- package/dist/debouncer.js +99 -86
- package/dist/event-client.d.ts +8 -11
- package/dist/event-client.js +1 -2
- package/dist/index.js +1 -1
- package/dist/queuer.d.ts +8 -10
- package/dist/queuer.js +277 -207
- package/dist/rate-limiter.d.ts +6 -9
- package/dist/rate-limiter.js +127 -109
- package/dist/throttler.d.ts +6 -9
- package/dist/throttler.js +127 -90
- package/dist/types.d.ts +4 -6
- package/dist/utils.d.ts +3 -6
- package/dist/utils.js +1 -2
- package/package.json +23 -70
- package/dist/async-batcher.cjs +0 -337
- package/dist/async-batcher.cjs.map +0 -1
- package/dist/async-batcher.d.cts +0 -344
- package/dist/async-batcher.js.map +0 -1
- package/dist/async-debouncer.cjs +0 -330
- package/dist/async-debouncer.cjs.map +0 -1
- package/dist/async-debouncer.d.cts +0 -300
- package/dist/async-debouncer.js.map +0 -1
- package/dist/async-queuer.cjs +0 -484
- package/dist/async-queuer.cjs.map +0 -1
- package/dist/async-queuer.d.cts +0 -440
- package/dist/async-queuer.js.map +0 -1
- package/dist/async-rate-limiter.cjs +0 -373
- package/dist/async-rate-limiter.cjs.map +0 -1
- package/dist/async-rate-limiter.d.cts +0 -357
- package/dist/async-rate-limiter.js.map +0 -1
- package/dist/async-retryer.cjs +0 -374
- package/dist/async-retryer.cjs.map +0 -1
- package/dist/async-retryer.d.cts +0 -319
- package/dist/async-retryer.js.map +0 -1
- package/dist/async-throttler.cjs +0 -347
- package/dist/async-throttler.cjs.map +0 -1
- package/dist/async-throttler.d.cts +0 -320
- package/dist/async-throttler.js.map +0 -1
- package/dist/batcher.cjs +0 -200
- package/dist/batcher.cjs.map +0 -1
- package/dist/batcher.d.cts +0 -180
- package/dist/batcher.js.map +0 -1
- package/dist/debouncer.cjs +0 -203
- package/dist/debouncer.cjs.map +0 -1
- package/dist/debouncer.d.cts +0 -167
- package/dist/debouncer.js.map +0 -1
- package/dist/event-client.cjs +0 -64
- package/dist/event-client.cjs.map +0 -1
- package/dist/event-client.d.cts +0 -66
- package/dist/event-client.js.map +0 -1
- package/dist/index.cjs +0 -52
- package/dist/index.d.cts +0 -15
- package/dist/queuer.cjs +0 -401
- package/dist/queuer.cjs.map +0 -1
- package/dist/queuer.d.cts +0 -345
- package/dist/queuer.js.map +0 -1
- package/dist/rate-limiter.cjs +0 -263
- package/dist/rate-limiter.cjs.map +0 -1
- package/dist/rate-limiter.d.cts +0 -215
- package/dist/rate-limiter.js.map +0 -1
- package/dist/throttler.cjs +0 -215
- package/dist/throttler.cjs.map +0 -1
- package/dist/throttler.d.cts +0 -207
- package/dist/throttler.js.map +0 -1
- package/dist/types.cjs +0 -0
- package/dist/types.d.cts +0 -13
- package/dist/utils.cjs +0 -14
- package/dist/utils.cjs.map +0 -1
- package/dist/utils.d.cts +0 -8
- package/dist/utils.js.map +0 -1
- package/src/async-batcher.ts +0 -594
- package/src/async-debouncer.ts +0 -565
- package/src/async-queuer.ts +0 -925
- package/src/async-rate-limiter.ts +0 -647
- package/src/async-retryer.ts +0 -684
- package/src/async-throttler.ts +0 -633
- package/src/batcher.ts +0 -329
- package/src/debouncer.ts +0 -334
- package/src/event-client.ts +0 -129
- package/src/index.ts +0 -24
- package/src/queuer.ts +0 -740
- package/src/rate-limiter.ts +0 -429
- package/src/throttler.ts +0 -380
- package/src/types.ts +0 -12
- package/src/utils.ts +0 -12
package/src/async-throttler.ts
DELETED
|
@@ -1,633 +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 AsyncThrottlerState<TFn extends AnyAsyncFunction> {
|
|
9
|
-
/**
|
|
10
|
-
* Number of function executions that have resulted in errors
|
|
11
|
-
*/
|
|
12
|
-
errorCount: number
|
|
13
|
-
/**
|
|
14
|
-
* Whether the throttled function is currently executing asynchronously
|
|
15
|
-
*/
|
|
16
|
-
isExecuting: boolean
|
|
17
|
-
/**
|
|
18
|
-
* Whether the throttler is waiting for the timeout to trigger execution
|
|
19
|
-
*/
|
|
20
|
-
isPending: boolean
|
|
21
|
-
/**
|
|
22
|
-
* The arguments from the most recent call to maybeExecute
|
|
23
|
-
*/
|
|
24
|
-
lastArgs: Parameters<TFn> | undefined
|
|
25
|
-
/**
|
|
26
|
-
* Timestamp of the last function execution in milliseconds
|
|
27
|
-
*/
|
|
28
|
-
lastExecutionTime: number
|
|
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
|
-
* Timestamp when the next execution can occur in milliseconds
|
|
39
|
-
*/
|
|
40
|
-
nextExecutionTime: number | undefined
|
|
41
|
-
/**
|
|
42
|
-
* Number of function executions that have completed (either successfully or with errors)
|
|
43
|
-
*/
|
|
44
|
-
settleCount: number
|
|
45
|
-
/**
|
|
46
|
-
* Current execution status - 'idle' when not active, 'pending' when waiting, 'executing' when running, 'settled' when completed
|
|
47
|
-
*/
|
|
48
|
-
status: 'disabled' | 'idle' | 'pending' | 'executing' | 'settled'
|
|
49
|
-
/**
|
|
50
|
-
* Number of function executions that have completed successfully
|
|
51
|
-
*/
|
|
52
|
-
successCount: number
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function getDefaultAsyncThrottlerState<
|
|
56
|
-
TFn extends AnyAsyncFunction,
|
|
57
|
-
>(): AsyncThrottlerState<TFn> {
|
|
58
|
-
return {
|
|
59
|
-
errorCount: 0,
|
|
60
|
-
isExecuting: false,
|
|
61
|
-
isPending: false,
|
|
62
|
-
lastArgs: undefined,
|
|
63
|
-
lastExecutionTime: 0,
|
|
64
|
-
lastResult: undefined,
|
|
65
|
-
maybeExecuteCount: 0,
|
|
66
|
-
nextExecutionTime: undefined,
|
|
67
|
-
settleCount: 0,
|
|
68
|
-
status: 'idle',
|
|
69
|
-
successCount: 0,
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Options for configuring an async throttled function
|
|
75
|
-
*/
|
|
76
|
-
export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
|
|
77
|
-
/**
|
|
78
|
-
* Options for configuring the underlying async retryer
|
|
79
|
-
*/
|
|
80
|
-
asyncRetryerOptions?: AsyncRetryerOptions<TFn>
|
|
81
|
-
/**
|
|
82
|
-
* Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
83
|
-
* Can be a boolean or a function that returns a boolean.
|
|
84
|
-
* Defaults to true.
|
|
85
|
-
*/
|
|
86
|
-
enabled?: boolean | ((throttler: AsyncThrottler<TFn>) => boolean)
|
|
87
|
-
/**
|
|
88
|
-
* Initial state for the async throttler
|
|
89
|
-
*/
|
|
90
|
-
initialState?: Partial<AsyncThrottlerState<TFn>>
|
|
91
|
-
/**
|
|
92
|
-
* Optional key to identify this async throttler instance.
|
|
93
|
-
* If provided, the async throttler will be identified by this key in the devtools and PacerProvider if applicable.
|
|
94
|
-
*/
|
|
95
|
-
key?: string
|
|
96
|
-
/**
|
|
97
|
-
* Whether to execute the function immediately when called
|
|
98
|
-
* Defaults to true
|
|
99
|
-
*/
|
|
100
|
-
leading?: boolean
|
|
101
|
-
/**
|
|
102
|
-
* Optional error handler for when the throttled function throws.
|
|
103
|
-
* If provided, the handler will be called with the error and throttler instance.
|
|
104
|
-
* This can be used alongside throwOnError - the handler will be called before any error is thrown.
|
|
105
|
-
*/
|
|
106
|
-
onError?: (
|
|
107
|
-
error: Error,
|
|
108
|
-
args: Parameters<TFn>,
|
|
109
|
-
asyncThrottler: AsyncThrottler<TFn>,
|
|
110
|
-
) => void
|
|
111
|
-
/**
|
|
112
|
-
* Optional function to call when the throttled function is executed
|
|
113
|
-
*/
|
|
114
|
-
onSettled?: (
|
|
115
|
-
args: Parameters<TFn>,
|
|
116
|
-
asyncThrottler: AsyncThrottler<TFn>,
|
|
117
|
-
) => void
|
|
118
|
-
/**
|
|
119
|
-
* Optional function to call when the throttled function is executed
|
|
120
|
-
*/
|
|
121
|
-
onSuccess?: (
|
|
122
|
-
result: ReturnType<TFn>,
|
|
123
|
-
args: Parameters<TFn>,
|
|
124
|
-
asyncThrottler: AsyncThrottler<TFn>,
|
|
125
|
-
) => void
|
|
126
|
-
/**
|
|
127
|
-
* Whether to throw errors when they occur.
|
|
128
|
-
* Defaults to true if no onError handler is provided, false if an onError handler is provided.
|
|
129
|
-
* Can be explicitly set to override these defaults.
|
|
130
|
-
*/
|
|
131
|
-
throwOnError?: boolean
|
|
132
|
-
/**
|
|
133
|
-
* Whether to execute the function on the trailing edge of the wait period
|
|
134
|
-
* Defaults to true
|
|
135
|
-
*/
|
|
136
|
-
trailing?: boolean
|
|
137
|
-
/**
|
|
138
|
-
* Time window in milliseconds during which the function can only be executed once.
|
|
139
|
-
* Can be a number or a function that returns a number.
|
|
140
|
-
* Defaults to 0ms
|
|
141
|
-
*/
|
|
142
|
-
wait: number | ((throttler: AsyncThrottler<TFn>) => number)
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Utility function for sharing common `AsyncThrottlerOptions` options between different `AsyncThrottler` instances.
|
|
147
|
-
*/
|
|
148
|
-
export function asyncThrottlerOptions<
|
|
149
|
-
TFn extends AnyAsyncFunction = AnyAsyncFunction,
|
|
150
|
-
TOptions extends Partial<AsyncThrottlerOptions<TFn>> = Partial<
|
|
151
|
-
AsyncThrottlerOptions<TFn>
|
|
152
|
-
>,
|
|
153
|
-
>(options: TOptions): TOptions {
|
|
154
|
-
return options
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
type AsyncThrottlerOptionsWithOptionalCallbacks = OptionalKeys<
|
|
158
|
-
AsyncThrottlerOptions<any>,
|
|
159
|
-
'initialState' | 'onError' | 'onSettled' | 'onSuccess'
|
|
160
|
-
>
|
|
161
|
-
|
|
162
|
-
const defaultOptions: AsyncThrottlerOptionsWithOptionalCallbacks = {
|
|
163
|
-
asyncRetryerOptions: {
|
|
164
|
-
maxAttempts: 1,
|
|
165
|
-
},
|
|
166
|
-
enabled: true,
|
|
167
|
-
leading: true,
|
|
168
|
-
trailing: true,
|
|
169
|
-
wait: 0,
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* A class that creates an async throttled function.
|
|
174
|
-
*
|
|
175
|
-
* Async vs Sync Versions:
|
|
176
|
-
* The async version provides advanced features over the sync Throttler:
|
|
177
|
-
* - Returns promises that can be awaited for throttled function results
|
|
178
|
-
* - Built-in retry support via AsyncRetryer integration
|
|
179
|
-
* - Abort support to cancel in-flight executions
|
|
180
|
-
* - Cancel support to prevent pending executions from starting
|
|
181
|
-
* - Comprehensive error handling with onError callbacks and throwOnError control
|
|
182
|
-
* - Detailed execution tracking (success/error/settle counts)
|
|
183
|
-
* - Waits for ongoing executions to complete before scheduling the next one
|
|
184
|
-
*
|
|
185
|
-
* The sync Throttler is lighter weight and simpler when you don't need async features,
|
|
186
|
-
* return values, or execution control.
|
|
187
|
-
*
|
|
188
|
-
* What is Throttling?
|
|
189
|
-
* Throttling limits how often a function can be executed, allowing only one execution within a specified time window.
|
|
190
|
-
* Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
|
|
191
|
-
* regular interval regardless of how often it's called.
|
|
192
|
-
*
|
|
193
|
-
* This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to
|
|
194
|
-
* ensure a maximum execution frequency.
|
|
195
|
-
*
|
|
196
|
-
* Error Handling:
|
|
197
|
-
* - If an `onError` handler is provided, it will be called with the error and throttler instance
|
|
198
|
-
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
199
|
-
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
200
|
-
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
201
|
-
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
202
|
-
*
|
|
203
|
-
* State Management:
|
|
204
|
-
* - Uses TanStack Store for reactive state management
|
|
205
|
-
* - Use `initialState` to provide initial state values when creating the async throttler
|
|
206
|
-
* - Use `onSuccess` callback to react to successful function execution and implement custom logic
|
|
207
|
-
* - Use `onError` callback to react to function execution errors and implement custom error handling
|
|
208
|
-
* - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
|
|
209
|
-
* - The state includes error count, execution status, last execution time, and success/settle counts
|
|
210
|
-
* - State can be accessed via `asyncThrottler.store.state` when using the class directly
|
|
211
|
-
* - When using framework adapters (React/Solid), state is accessed from `asyncThrottler.state`
|
|
212
|
-
*
|
|
213
|
-
* @example
|
|
214
|
-
* ```ts
|
|
215
|
-
* const throttler = new AsyncThrottler(async (value: string) => {
|
|
216
|
-
* const result = await saveToAPI(value);
|
|
217
|
-
* return result; // Return value is preserved
|
|
218
|
-
* }, {
|
|
219
|
-
* wait: 1000,
|
|
220
|
-
* onError: (error) => {
|
|
221
|
-
* console.error('API call failed:', error);
|
|
222
|
-
* }
|
|
223
|
-
* });
|
|
224
|
-
*
|
|
225
|
-
* // Will only execute once per second no matter how often called
|
|
226
|
-
* // Returns the API response directly
|
|
227
|
-
* const result = await throttler.maybeExecute(inputElement.value);
|
|
228
|
-
* ```
|
|
229
|
-
*/
|
|
230
|
-
export class AsyncThrottler<TFn extends AnyAsyncFunction> {
|
|
231
|
-
readonly store: Store<Readonly<AsyncThrottlerState<TFn>>> = new Store<
|
|
232
|
-
AsyncThrottlerState<TFn>
|
|
233
|
-
>(getDefaultAsyncThrottlerState<TFn>())
|
|
234
|
-
key: string | undefined
|
|
235
|
-
options: AsyncThrottlerOptions<TFn>
|
|
236
|
-
asyncRetryers = new Map<number, AsyncRetryer<TFn>>()
|
|
237
|
-
#timeoutId: ReturnType<typeof setTimeout> | null = null
|
|
238
|
-
#resolvePreviousPromise:
|
|
239
|
-
| ((value?: ReturnType<TFn> | undefined) => void)
|
|
240
|
-
| null = null
|
|
241
|
-
|
|
242
|
-
constructor(
|
|
243
|
-
public fn: TFn,
|
|
244
|
-
initialOptions: AsyncThrottlerOptions<TFn>,
|
|
245
|
-
) {
|
|
246
|
-
this.key = initialOptions.key
|
|
247
|
-
this.options = {
|
|
248
|
-
...defaultOptions,
|
|
249
|
-
...initialOptions,
|
|
250
|
-
throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,
|
|
251
|
-
}
|
|
252
|
-
this.#setState(this.options.initialState ?? {})
|
|
253
|
-
|
|
254
|
-
if (this.key) {
|
|
255
|
-
pacerEventClient.on('d-AsyncThrottler', (event) => {
|
|
256
|
-
if (event.payload.key !== this.key) return
|
|
257
|
-
this.#setState(
|
|
258
|
-
event.payload.store.state as Partial<AsyncThrottlerState<TFn>>,
|
|
259
|
-
)
|
|
260
|
-
this.setOptions(
|
|
261
|
-
event.payload.options as Partial<AsyncThrottlerOptions<TFn>>,
|
|
262
|
-
)
|
|
263
|
-
})
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
/**
|
|
268
|
-
* Updates the async throttler options
|
|
269
|
-
*/
|
|
270
|
-
setOptions = (newOptions: Partial<AsyncThrottlerOptions<TFn>>): void => {
|
|
271
|
-
this.options = { ...this.options, ...newOptions }
|
|
272
|
-
|
|
273
|
-
// End the pending state if the throttler is disabled
|
|
274
|
-
if (!this.#getEnabled()) {
|
|
275
|
-
this.cancel()
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
#setState = (newState: Partial<AsyncThrottlerState<TFn>>): void => {
|
|
280
|
-
this.store.setState((state) => {
|
|
281
|
-
const combinedState = {
|
|
282
|
-
...state,
|
|
283
|
-
...newState,
|
|
284
|
-
}
|
|
285
|
-
const { isPending, isExecuting, settleCount } = combinedState
|
|
286
|
-
return {
|
|
287
|
-
...combinedState,
|
|
288
|
-
status: !this.#getEnabled()
|
|
289
|
-
? 'disabled'
|
|
290
|
-
: isPending
|
|
291
|
-
? 'pending'
|
|
292
|
-
: isExecuting
|
|
293
|
-
? 'executing'
|
|
294
|
-
: settleCount > 0
|
|
295
|
-
? 'settled'
|
|
296
|
-
: 'idle',
|
|
297
|
-
}
|
|
298
|
-
})
|
|
299
|
-
emitChange('AsyncThrottler', this)
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
/**
|
|
303
|
-
* Returns the current enabled state of the async throttler
|
|
304
|
-
*/
|
|
305
|
-
#getEnabled = (): boolean => {
|
|
306
|
-
return !!parseFunctionOrValue(this.options.enabled, this)
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
/**
|
|
310
|
-
* Returns the current wait time in milliseconds
|
|
311
|
-
*/
|
|
312
|
-
#getWait = (): number => {
|
|
313
|
-
return parseFunctionOrValue(this.options.wait, this)
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
/**
|
|
317
|
-
* Attempts to execute the throttled function. The execution behavior depends on the throttler options:
|
|
318
|
-
*
|
|
319
|
-
* - If enough time has passed since the last execution (>= wait period):
|
|
320
|
-
* - With leading=true: Executes immediately
|
|
321
|
-
* - With leading=false: Waits for the next trailing execution
|
|
322
|
-
*
|
|
323
|
-
* - If within the wait period:
|
|
324
|
-
* - With trailing=true: Schedules execution for end of wait period
|
|
325
|
-
* - With trailing=false: Drops the execution
|
|
326
|
-
*
|
|
327
|
-
* @example
|
|
328
|
-
* ```ts
|
|
329
|
-
* const throttled = new AsyncThrottler(fn, { wait: 1000 });
|
|
330
|
-
*
|
|
331
|
-
* // First call executes immediately
|
|
332
|
-
* await throttled.maybeExecute('a', 'b');
|
|
333
|
-
*
|
|
334
|
-
* // Call during wait period - gets throttled
|
|
335
|
-
* await throttled.maybeExecute('c', 'd');
|
|
336
|
-
* ```
|
|
337
|
-
*/
|
|
338
|
-
maybeExecute = async (
|
|
339
|
-
...args: Parameters<TFn>
|
|
340
|
-
): Promise<ReturnType<TFn> | undefined> => {
|
|
341
|
-
if (!this.#getEnabled()) return undefined
|
|
342
|
-
|
|
343
|
-
this.#resolvePreviousPromiseInternal()
|
|
344
|
-
|
|
345
|
-
this.#setState({
|
|
346
|
-
maybeExecuteCount: this.store.state.maybeExecuteCount + 1,
|
|
347
|
-
lastArgs: args, // store the arguments for potential trailing execution
|
|
348
|
-
})
|
|
349
|
-
|
|
350
|
-
const wait = this.#getWait()
|
|
351
|
-
const thisMaybeExecuteNumber = this.store.state.maybeExecuteCount
|
|
352
|
-
|
|
353
|
-
// Wait for the wait period for the previous execution to complete if it's still running
|
|
354
|
-
for (
|
|
355
|
-
let maxNumIterations = wait / 10;
|
|
356
|
-
this.store.state.isExecuting && maxNumIterations > 0;
|
|
357
|
-
maxNumIterations--
|
|
358
|
-
) {
|
|
359
|
-
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
360
|
-
if (this.store.state.maybeExecuteCount !== thisMaybeExecuteNumber) {
|
|
361
|
-
// cancel the current maybeExecute loop because a new maybeExecute call was made
|
|
362
|
-
return this.store.state.lastResult
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
const now = Date.now()
|
|
367
|
-
const timeSinceLastExecution = now - this.store.state.lastExecutionTime
|
|
368
|
-
|
|
369
|
-
if (
|
|
370
|
-
this.options.leading &&
|
|
371
|
-
!this.store.state.isPending &&
|
|
372
|
-
timeSinceLastExecution >= wait
|
|
373
|
-
) {
|
|
374
|
-
await this.#execute(...args) // Leading EXECUTE!
|
|
375
|
-
} else if (this.options.trailing) {
|
|
376
|
-
// replace old pending execution with a new one
|
|
377
|
-
this.cancel()
|
|
378
|
-
this.#setState({
|
|
379
|
-
isPending: true,
|
|
380
|
-
})
|
|
381
|
-
|
|
382
|
-
// Set up new trailing execution
|
|
383
|
-
return new Promise((resolve, reject) => {
|
|
384
|
-
this.#resolvePreviousPromise = resolve
|
|
385
|
-
|
|
386
|
-
const newTimeSinceLastExecution = this.store.state.lastExecutionTime
|
|
387
|
-
? now - this.store.state.lastExecutionTime
|
|
388
|
-
: 0
|
|
389
|
-
const timeoutDuration = Math.max(0, wait - newTimeSinceLastExecution)
|
|
390
|
-
|
|
391
|
-
this.#timeoutId = setTimeout(async () => {
|
|
392
|
-
this.#clearTimeout()
|
|
393
|
-
if (this.store.state.lastArgs !== undefined) {
|
|
394
|
-
try {
|
|
395
|
-
await this.#execute(...this.store.state.lastArgs) // Trailing EXECUTE!
|
|
396
|
-
} catch (error) {
|
|
397
|
-
reject(error)
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
this.#resolvePreviousPromise = null
|
|
401
|
-
resolve(this.store.state.lastResult)
|
|
402
|
-
}, timeoutDuration)
|
|
403
|
-
})
|
|
404
|
-
}
|
|
405
|
-
return this.store.state.lastResult
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
#execute = async (
|
|
409
|
-
...args: Parameters<TFn>
|
|
410
|
-
): Promise<ReturnType<TFn> | undefined> => {
|
|
411
|
-
if (!this.#getEnabled()) return undefined
|
|
412
|
-
|
|
413
|
-
const currentMaybeExecute = this.store.state.maybeExecuteCount
|
|
414
|
-
|
|
415
|
-
try {
|
|
416
|
-
this.#setState({ isExecuting: true })
|
|
417
|
-
const currentAsyncRetryer = new AsyncRetryer(this.fn, {
|
|
418
|
-
...this.options.asyncRetryerOptions,
|
|
419
|
-
key: `${this.key}-retryer-${currentMaybeExecute}`,
|
|
420
|
-
})
|
|
421
|
-
this.asyncRetryers.set(currentMaybeExecute, currentAsyncRetryer)
|
|
422
|
-
const result = await currentAsyncRetryer.execute(...args) // EXECUTE!
|
|
423
|
-
this.#setState({
|
|
424
|
-
lastResult: result,
|
|
425
|
-
successCount: this.store.state.successCount + 1,
|
|
426
|
-
})
|
|
427
|
-
this.options.onSuccess?.(result as ReturnType<TFn>, args, this)
|
|
428
|
-
} catch (error) {
|
|
429
|
-
this.#setState({
|
|
430
|
-
errorCount: this.store.state.errorCount + 1,
|
|
431
|
-
})
|
|
432
|
-
this.options.onError?.(error as Error, args, this)
|
|
433
|
-
if (this.options.throwOnError) {
|
|
434
|
-
throw error
|
|
435
|
-
}
|
|
436
|
-
} finally {
|
|
437
|
-
this.asyncRetryers.delete(currentMaybeExecute) // dispose retryer
|
|
438
|
-
const lastExecutionTime = Date.now()
|
|
439
|
-
const wait = this.#getWait()
|
|
440
|
-
const nextExecutionTime = lastExecutionTime + wait
|
|
441
|
-
this.#setState({
|
|
442
|
-
isExecuting: false,
|
|
443
|
-
isPending: !!this.#timeoutId,
|
|
444
|
-
settleCount: this.store.state.settleCount + 1,
|
|
445
|
-
lastExecutionTime,
|
|
446
|
-
nextExecutionTime,
|
|
447
|
-
})
|
|
448
|
-
this.options.onSettled?.(args, this)
|
|
449
|
-
setTimeout(() => {
|
|
450
|
-
if (!this.store.state.isPending) {
|
|
451
|
-
// clear nextExecutionTime if there is no pending execution
|
|
452
|
-
this.#setState({ nextExecutionTime: undefined })
|
|
453
|
-
}
|
|
454
|
-
}, wait)
|
|
455
|
-
}
|
|
456
|
-
return this.store.state.lastResult
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
/**
|
|
460
|
-
* Processes the current pending execution immediately
|
|
461
|
-
*/
|
|
462
|
-
flush = async (): Promise<ReturnType<TFn> | undefined> => {
|
|
463
|
-
if (this.store.state.isPending && this.store.state.lastArgs) {
|
|
464
|
-
// Store the pending promise resolver before clearing timeout
|
|
465
|
-
const resolvePromise = this.#resolvePreviousPromise
|
|
466
|
-
|
|
467
|
-
// Clear timeout and state without resolving the promise
|
|
468
|
-
this.#clearTimeout()
|
|
469
|
-
this.#setState({
|
|
470
|
-
isPending: false,
|
|
471
|
-
})
|
|
472
|
-
|
|
473
|
-
const result = await this.#execute(...this.store.state.lastArgs)
|
|
474
|
-
|
|
475
|
-
// Resolve the pending promise with the result
|
|
476
|
-
if (resolvePromise) {
|
|
477
|
-
resolvePromise(result)
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
return result
|
|
481
|
-
}
|
|
482
|
-
return undefined
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
#resolvePreviousPromiseInternal = (): void => {
|
|
486
|
-
if (this.#resolvePreviousPromise) {
|
|
487
|
-
this.#resolvePreviousPromise(this.store.state.lastResult)
|
|
488
|
-
this.#resolvePreviousPromise = null
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
#clearTimeout = (): void => {
|
|
493
|
-
if (this.#timeoutId) {
|
|
494
|
-
clearTimeout(this.#timeoutId)
|
|
495
|
-
this.#timeoutId = null
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
/**
|
|
500
|
-
* Returns the AbortSignal for a specific execution.
|
|
501
|
-
* If no maybeExecuteCount is provided, returns the signal for the most recent execution.
|
|
502
|
-
* Returns null if no execution is found or not currently executing.
|
|
503
|
-
*
|
|
504
|
-
* @param maybeExecuteCount - Optional specific execution to get signal for
|
|
505
|
-
* @example
|
|
506
|
-
* ```typescript
|
|
507
|
-
* const throttler = new AsyncThrottler(
|
|
508
|
-
* async (data: string) => {
|
|
509
|
-
* const signal = throttler.getAbortSignal()
|
|
510
|
-
* if (signal) {
|
|
511
|
-
* const response = await fetch('/api/save', {
|
|
512
|
-
* method: 'POST',
|
|
513
|
-
* body: data,
|
|
514
|
-
* signal
|
|
515
|
-
* })
|
|
516
|
-
* return response.json()
|
|
517
|
-
* }
|
|
518
|
-
* },
|
|
519
|
-
* { wait: 1000 }
|
|
520
|
-
* )
|
|
521
|
-
* ```
|
|
522
|
-
*/
|
|
523
|
-
getAbortSignal = (maybeExecuteCount?: number): AbortSignal | null => {
|
|
524
|
-
const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount
|
|
525
|
-
const retryer = this.asyncRetryers.get(count)
|
|
526
|
-
return retryer?.getAbortSignal() ?? null
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
/**
|
|
530
|
-
* Aborts all ongoing executions with the internal abort controllers.
|
|
531
|
-
* Does NOT cancel any pending execution that have not started yet.
|
|
532
|
-
*/
|
|
533
|
-
abort = (): void => {
|
|
534
|
-
this.asyncRetryers.forEach((retryer) => retryer.abort())
|
|
535
|
-
this.asyncRetryers.clear()
|
|
536
|
-
this.#setState({ isExecuting: false })
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
/**
|
|
540
|
-
* Cancels any pending execution that have not started yet.
|
|
541
|
-
* Does NOT abort any execution already in progress.
|
|
542
|
-
*/
|
|
543
|
-
cancel = (): void => {
|
|
544
|
-
this.#clearTimeout()
|
|
545
|
-
if (this.#resolvePreviousPromise) {
|
|
546
|
-
this.#resolvePreviousPromiseInternal()
|
|
547
|
-
this.#resolvePreviousPromise = null
|
|
548
|
-
}
|
|
549
|
-
this.#setState({
|
|
550
|
-
isPending: false,
|
|
551
|
-
})
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
/**
|
|
555
|
-
* Resets the debouncer state to its default values
|
|
556
|
-
*/
|
|
557
|
-
reset = (): void => {
|
|
558
|
-
this.#setState(getDefaultAsyncThrottlerState<TFn>())
|
|
559
|
-
this.asyncRetryers.forEach((retryer) => retryer.reset())
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
/**
|
|
564
|
-
* Creates an async throttled function that limits how often the function can execute.
|
|
565
|
-
* The throttled function will execute at most once per wait period, even if called multiple times.
|
|
566
|
-
* If called while executing, it will wait until execution completes before scheduling the next call.
|
|
567
|
-
*
|
|
568
|
-
* Async vs Sync Versions:
|
|
569
|
-
* The async version provides advanced features over the sync throttle function:
|
|
570
|
-
* - Returns promises that can be awaited for throttled function results
|
|
571
|
-
* - Built-in retry support via AsyncRetryer integration
|
|
572
|
-
* - Abort support to cancel in-flight executions
|
|
573
|
-
* - Cancel support to prevent pending executions from starting
|
|
574
|
-
* - Comprehensive error handling with onError callbacks and throwOnError control
|
|
575
|
-
* - Detailed execution tracking (success/error/settle counts)
|
|
576
|
-
* - Waits for ongoing executions to complete before scheduling the next one
|
|
577
|
-
*
|
|
578
|
-
* The sync throttle function is lighter weight and simpler when you don't need async features,
|
|
579
|
-
* return values, or execution control.
|
|
580
|
-
*
|
|
581
|
-
* What is Throttling?
|
|
582
|
-
* Throttling limits how often a function can be executed, allowing only one execution within a specified time window.
|
|
583
|
-
* Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
|
|
584
|
-
* regular interval regardless of how often it's called.
|
|
585
|
-
*
|
|
586
|
-
* Configuration Options:
|
|
587
|
-
* - `wait`: Time window in milliseconds during which the function can only execute once (required)
|
|
588
|
-
* - `leading`: Execute immediately when called (default: true)
|
|
589
|
-
* - `trailing`: Execute on the trailing edge of the wait period (default: true)
|
|
590
|
-
* - `enabled`: Whether the throttler is enabled (default: true)
|
|
591
|
-
* - `asyncRetryerOptions`: Configure retry behavior for executions
|
|
592
|
-
*
|
|
593
|
-
* Error Handling:
|
|
594
|
-
* - If an `onError` handler is provided, it will be called with the error and throttler instance
|
|
595
|
-
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
596
|
-
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
597
|
-
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
598
|
-
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
599
|
-
*
|
|
600
|
-
* State Management:
|
|
601
|
-
* - Uses TanStack Store for reactive state management
|
|
602
|
-
* - Use `initialState` to provide initial state values when creating the async throttler
|
|
603
|
-
* - Use `onSuccess` callback to react to successful function execution and implement custom logic
|
|
604
|
-
* - Use `onError` callback to react to function execution errors and implement custom error handling
|
|
605
|
-
* - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
|
|
606
|
-
* - The state includes error count, execution status, last execution time, and success/settle counts
|
|
607
|
-
* - State can be accessed via the underlying AsyncThrottler instance's `store.state` property
|
|
608
|
-
* - When using framework adapters (React/Solid), state is accessed from the hook's state property
|
|
609
|
-
*
|
|
610
|
-
* @example
|
|
611
|
-
* ```ts
|
|
612
|
-
* const throttled = asyncThrottle(async (value: string) => {
|
|
613
|
-
* const result = await saveToAPI(value);
|
|
614
|
-
* return result; // Return value is preserved
|
|
615
|
-
* }, {
|
|
616
|
-
* wait: 1000,
|
|
617
|
-
* onError: (error) => {
|
|
618
|
-
* console.error('API call failed:', error);
|
|
619
|
-
* }
|
|
620
|
-
* });
|
|
621
|
-
*
|
|
622
|
-
* // This will execute at most once per second
|
|
623
|
-
* // Returns the API response directly
|
|
624
|
-
* const result = await throttled(inputElement.value);
|
|
625
|
-
* ```
|
|
626
|
-
*/
|
|
627
|
-
export function asyncThrottle<TFn extends AnyAsyncFunction>(
|
|
628
|
-
fn: TFn,
|
|
629
|
-
initialOptions: AsyncThrottlerOptions<TFn>,
|
|
630
|
-
) {
|
|
631
|
-
const asyncThrottler = new AsyncThrottler(fn, initialOptions)
|
|
632
|
-
return asyncThrottler.maybeExecute
|
|
633
|
-
}
|