@tanstack/pacer 0.2.0 → 0.4.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/dist/cjs/async-debouncer.cjs +78 -45
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +60 -24
- package/dist/cjs/async-queuer.cjs +53 -3
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +28 -3
- package/dist/cjs/async-rate-limiter.cjs +75 -38
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +76 -24
- package/dist/cjs/async-throttler.cjs +85 -57
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +66 -25
- package/dist/cjs/debouncer.cjs +12 -14
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +10 -9
- package/dist/cjs/queuer.cjs +51 -1
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +30 -1
- package/dist/cjs/rate-limiter.cjs +19 -9
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +31 -11
- package/dist/cjs/throttler.cjs +29 -36
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +16 -17
- package/dist/cjs/types.d.cts +2 -6
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +1 -1
- package/dist/esm/async-debouncer.d.ts +60 -24
- package/dist/esm/async-debouncer.js +78 -45
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +28 -3
- package/dist/esm/async-queuer.js +53 -3
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +76 -24
- package/dist/esm/async-rate-limiter.js +75 -38
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +66 -25
- package/dist/esm/async-throttler.js +85 -57
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/debouncer.d.ts +10 -9
- package/dist/esm/debouncer.js +12 -14
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/queuer.d.ts +30 -1
- package/dist/esm/queuer.js +51 -1
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +31 -11
- package/dist/esm/rate-limiter.js +19 -9
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +16 -17
- package/dist/esm/throttler.js +29 -36
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/types.d.ts +2 -6
- package/dist/esm/utils.d.ts +1 -1
- package/dist/esm/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/async-debouncer.ts +130 -81
- package/src/async-queuer.ts +93 -8
- package/src/async-rate-limiter.ts +141 -67
- package/src/async-throttler.ts +152 -94
- package/src/debouncer.ts +26 -33
- package/src/queuer.ts +92 -4
- package/src/rate-limiter.ts +56 -32
- package/src/throttler.ts +45 -53
- package/src/types.ts +2 -10
- package/src/utils.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"throttler.cjs","sources":["../../src/throttler.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions
|
|
1
|
+
{"version":3,"file":"throttler.cjs","sources":["../../src/throttler.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (throttler: Throttler<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once\n */\n wait: number\n}\n\nconst defaultOptions: Required<ThrottlerOptions<any>> = {\n enabled: true,\n leading: true,\n onExecute: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<TFn extends AnyFunction> {\n private _executionCount = 0\n private _lastArgs: Parameters<TFn> | undefined\n private _lastExecutionTime = 0\n private _options: Required<ThrottlerOptions<TFn>>\n private _timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the throttler options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<ThrottlerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this.cancel()\n }\n }\n\n /**\n * Returns the current throttler options\n */\n getOptions(): Required<ThrottlerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute(...args: Parameters<TFn>): void {\n const now = Date.now()\n const timeSinceLastExecution = now - this._lastExecutionTime\n\n // Handle leading execution\n if (this._options.leading && timeSinceLastExecution >= this._options.wait) {\n this.executeFunction(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this._lastArgs = args\n\n // Set up trailing execution if not already scheduled\n if (!this._timeoutId && this._options.trailing) {\n const _timeSinceLastExecution = this._lastExecutionTime\n ? now - this._lastExecutionTime\n : 0\n const timeoutDuration = this._options.wait - _timeSinceLastExecution\n this._timeoutId = setTimeout(() => {\n if (this._lastArgs !== undefined) {\n this.executeFunction(...this._lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n private executeFunction(...args: Parameters<TFn>): void {\n if (!this._options.enabled) return\n this.fn(...args) // EXECUTE!\n this._executionCount++\n this._lastExecutionTime = Date.now()\n this._timeoutId = undefined\n this._lastArgs = undefined\n this._options.onExecute(this)\n }\n\n /**\n * Cancels any pending trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = undefined\n this._lastArgs = undefined\n }\n }\n\n /**\n * Returns the last execution time\n */\n getLastExecutionTime(): number {\n return this._lastExecutionTime\n }\n\n /**\n * Returns the next execution time\n */\n getNextExecutionTime(): number {\n return this._lastExecutionTime + this._options.wait\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns `true` if there is a pending execution\n */\n getIsPending(): boolean {\n return this._options.enabled && !!this._timeoutId\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * @example\n * ```ts\n * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: Omit<ThrottlerOptions<TFn>, 'enabled'>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute.bind(throttler)\n}\n"],"names":[],"mappings":";;AA+BA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AA6BO,MAAM,UAAmC;AAAA,EAO9C,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAQ,kBAAkB;AAE1B,SAAQ,qBAAqB;AAQ3B,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAkD;AAC3D,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAG9C,QAAA,CAAC,KAAK,SAAS,SAAS;AAC1B,WAAK,OAAO;AAAA,IAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAMF,aAA8C;AAC5C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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S,WAAW,CAAC,CAAC,KAAK;AAAA,EAAA;AAE3C;AA4BgB,SAAA,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;;;"}
|
package/dist/cjs/throttler.d.cts
CHANGED
|
@@ -2,7 +2,7 @@ import { AnyFunction } from './types.cjs';
|
|
|
2
2
|
/**
|
|
3
3
|
* Options for configuring a throttled function
|
|
4
4
|
*/
|
|
5
|
-
export interface ThrottlerOptions<TFn extends AnyFunction
|
|
5
|
+
export interface ThrottlerOptions<TFn extends AnyFunction> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
8
|
* Defaults to true.
|
|
@@ -16,7 +16,7 @@ export interface ThrottlerOptions<TFn extends AnyFunction, TArgs extends Paramet
|
|
|
16
16
|
/**
|
|
17
17
|
* Callback function that is called after the function is executed
|
|
18
18
|
*/
|
|
19
|
-
onExecute?: (throttler: Throttler<TFn
|
|
19
|
+
onExecute?: (throttler: Throttler<TFn>) => void;
|
|
20
20
|
/**
|
|
21
21
|
* Whether to execute on the trailing edge of the timeout.
|
|
22
22
|
* Defaults to true.
|
|
@@ -54,24 +54,23 @@ export interface ThrottlerOptions<TFn extends AnyFunction, TArgs extends Paramet
|
|
|
54
54
|
* throttler.maybeExecute('123'); // Throttled
|
|
55
55
|
* ```
|
|
56
56
|
*/
|
|
57
|
-
export declare class Throttler<TFn extends AnyFunction
|
|
57
|
+
export declare class Throttler<TFn extends AnyFunction> {
|
|
58
58
|
private fn;
|
|
59
59
|
private _executionCount;
|
|
60
60
|
private _lastArgs;
|
|
61
61
|
private _lastExecutionTime;
|
|
62
62
|
private _options;
|
|
63
63
|
private _timeoutId;
|
|
64
|
-
|
|
65
|
-
constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn, TArgs>);
|
|
64
|
+
constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn>);
|
|
66
65
|
/**
|
|
67
66
|
* Updates the throttler options
|
|
68
67
|
* Returns the new options state
|
|
69
68
|
*/
|
|
70
|
-
setOptions(newOptions: Partial<ThrottlerOptions<TFn
|
|
69
|
+
setOptions(newOptions: Partial<ThrottlerOptions<TFn>>): void;
|
|
71
70
|
/**
|
|
72
71
|
* Returns the current throttler options
|
|
73
72
|
*/
|
|
74
|
-
getOptions(): Required<ThrottlerOptions<TFn
|
|
73
|
+
getOptions(): Required<ThrottlerOptions<TFn>>;
|
|
75
74
|
/**
|
|
76
75
|
* Attempts to execute the throttled function. The execution behavior depends on the throttler options:
|
|
77
76
|
*
|
|
@@ -94,7 +93,7 @@ export declare class Throttler<TFn extends AnyFunction, TArgs extends Parameters
|
|
|
94
93
|
* throttled.maybeExecute('c', 'd');
|
|
95
94
|
* ```
|
|
96
95
|
*/
|
|
97
|
-
maybeExecute(...args:
|
|
96
|
+
maybeExecute(...args: Parameters<TFn>): void;
|
|
98
97
|
private executeFunction;
|
|
99
98
|
/**
|
|
100
99
|
* Cancels any pending trailing execution and clears internal state.
|
|
@@ -106,14 +105,6 @@ export declare class Throttler<TFn extends AnyFunction, TArgs extends Parameters
|
|
|
106
105
|
* Has no effect if there is no pending execution.
|
|
107
106
|
*/
|
|
108
107
|
cancel(): void;
|
|
109
|
-
/**
|
|
110
|
-
* Returns the number of times the function has been executed
|
|
111
|
-
*/
|
|
112
|
-
getExecutionCount(): number;
|
|
113
|
-
/**
|
|
114
|
-
* Returns `true` if there is a pending execution
|
|
115
|
-
*/
|
|
116
|
-
getIsPending(): boolean;
|
|
117
108
|
/**
|
|
118
109
|
* Returns the last execution time
|
|
119
110
|
*/
|
|
@@ -122,6 +113,14 @@ export declare class Throttler<TFn extends AnyFunction, TArgs extends Parameters
|
|
|
122
113
|
* Returns the next execution time
|
|
123
114
|
*/
|
|
124
115
|
getNextExecutionTime(): number;
|
|
116
|
+
/**
|
|
117
|
+
* Returns the number of times the function has been executed
|
|
118
|
+
*/
|
|
119
|
+
getExecutionCount(): number;
|
|
120
|
+
/**
|
|
121
|
+
* Returns `true` if there is a pending execution
|
|
122
|
+
*/
|
|
123
|
+
getIsPending(): boolean;
|
|
125
124
|
}
|
|
126
125
|
/**
|
|
127
126
|
* Creates a throttled function that limits how often the provided function can execute.
|
|
@@ -149,4 +148,4 @@ export declare class Throttler<TFn extends AnyFunction, TArgs extends Parameters
|
|
|
149
148
|
* });
|
|
150
149
|
* ```
|
|
151
150
|
*/
|
|
152
|
-
export declare function throttle<TFn extends AnyFunction
|
|
151
|
+
export declare function throttle<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<ThrottlerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => void;
|
package/dist/cjs/types.d.cts
CHANGED
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Represents a function that can be called with any arguments and returns any value.
|
|
3
|
-
* @template TArgs - The type of the arguments the function can be called with.
|
|
4
|
-
* @returns The return value of the function.
|
|
5
3
|
*/
|
|
6
|
-
export type AnyFunction
|
|
4
|
+
export type AnyFunction = (...args: Array<any>) => any;
|
|
7
5
|
/**
|
|
8
6
|
* Represents an asynchronous function that can be called with any arguments and returns a promise.
|
|
9
|
-
* @template TArgs - The type of the arguments the function can be called with.
|
|
10
|
-
* @returns A promise that resolves to the return value of the function.
|
|
11
7
|
*/
|
|
12
|
-
export type AnyAsyncFunction
|
|
8
|
+
export type AnyAsyncFunction = (...args: Array<any>) => Promise<any>;
|
package/dist/cjs/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["export function bindInstanceMethods<T extends Record<string, any>>(\n instance: T,\n) {\n return Object.getOwnPropertyNames(Object.getPrototypeOf(instance))\n .filter((key) => typeof instance[key as keyof T] === 'function')\n .reduce((acc: any, key) => {\n const method = instance[key as keyof T]\n if (typeof method === 'function') {\n acc[key] = method.bind(instance)\n }\n return acc\n }, {} as T)\n}\n"],"names":[],"mappings":";;AAAO,SAAS,oBACd,
|
|
1
|
+
{"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["export function bindInstanceMethods<T extends Record<string, any>>(\n instance: T,\n): T {\n return Object.getOwnPropertyNames(Object.getPrototypeOf(instance))\n .filter((key) => typeof instance[key as keyof T] === 'function')\n .reduce((acc: any, key) => {\n const method = instance[key as keyof T]\n if (typeof method === 'function') {\n acc[key] = method.bind(instance)\n }\n return acc\n }, {} as T)\n}\n"],"names":[],"mappings":";;AAAO,SAAS,oBACd,UACG;AACH,SAAO,OAAO,oBAAoB,OAAO,eAAe,QAAQ,CAAC,EAC9D,OAAO,CAAC,QAAQ,OAAO,SAAS,GAAc,MAAM,UAAU,EAC9D,OAAO,CAAC,KAAU,QAAQ;AACnB,UAAA,SAAS,SAAS,GAAc;AAClC,QAAA,OAAO,WAAW,YAAY;AAChC,UAAI,GAAG,IAAI,OAAO,KAAK,QAAQ;AAAA,IAAA;AAE1B,WAAA;AAAA,EACT,GAAG,EAAO;AACd;;"}
|
package/dist/cjs/utils.d.cts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function bindInstanceMethods<T extends Record<string, any>>(instance: T):
|
|
1
|
+
export declare function bindInstanceMethods<T extends Record<string, any>>(instance: T): T;
|
|
@@ -2,7 +2,7 @@ import { AnyAsyncFunction } from './types.js';
|
|
|
2
2
|
/**
|
|
3
3
|
* Options for configuring an async debounced function
|
|
4
4
|
*/
|
|
5
|
-
export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction
|
|
5
|
+
export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
8
|
* Defaults to true.
|
|
@@ -16,11 +16,15 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction, TArgs exten
|
|
|
16
16
|
/**
|
|
17
17
|
* Optional error handler for when the debounced function throws
|
|
18
18
|
*/
|
|
19
|
-
onError?: (error: unknown) => void;
|
|
19
|
+
onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void;
|
|
20
20
|
/**
|
|
21
|
-
* Optional
|
|
21
|
+
* Optional callback to call when the debounced function is executed
|
|
22
22
|
*/
|
|
23
|
-
|
|
23
|
+
onSettled?: (debouncer: AsyncDebouncer<TFn>) => void;
|
|
24
|
+
/**
|
|
25
|
+
* Optional callback to call when the debounced function is executed
|
|
26
|
+
*/
|
|
27
|
+
onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void;
|
|
24
28
|
/**
|
|
25
29
|
* Whether to execute on the trailing edge of the timeout.
|
|
26
30
|
* Defaults to true.
|
|
@@ -42,71 +46,103 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction, TArgs exten
|
|
|
42
46
|
* Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
|
|
43
47
|
* the function stops being called for the specified delay period.
|
|
44
48
|
*
|
|
49
|
+
* Unlike the non-async Debouncer, this async version supports returning values from the debounced function,
|
|
50
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
51
|
+
* instead of setting the result on a state variable from within the debounced function.
|
|
52
|
+
*
|
|
45
53
|
* @example
|
|
46
54
|
* ```ts
|
|
47
55
|
* const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
|
|
48
|
-
* await searchAPI(value);
|
|
56
|
+
* const results = await searchAPI(value);
|
|
57
|
+
* return results; // Return value is preserved
|
|
49
58
|
* }, { wait: 500 });
|
|
50
59
|
*
|
|
51
60
|
* // Called on each keystroke but only executes after 500ms of no typing
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
* });
|
|
61
|
+
* // Returns the API response directly
|
|
62
|
+
* const results = await asyncDebouncer.maybeExecute(inputElement.value);
|
|
55
63
|
* ```
|
|
56
64
|
*/
|
|
57
|
-
export declare class AsyncDebouncer<TFn extends AnyAsyncFunction
|
|
65
|
+
export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
58
66
|
private fn;
|
|
59
67
|
private _abortController;
|
|
60
|
-
private
|
|
68
|
+
private _canLeadingExecute;
|
|
69
|
+
private _errorCount;
|
|
61
70
|
private _isExecuting;
|
|
71
|
+
private _isPending;
|
|
62
72
|
private _lastArgs;
|
|
73
|
+
private _lastResult;
|
|
63
74
|
private _options;
|
|
75
|
+
private _settleCount;
|
|
76
|
+
private _successCount;
|
|
64
77
|
private _timeoutId;
|
|
65
|
-
|
|
66
|
-
constructor(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn, TArgs>);
|
|
78
|
+
constructor(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>);
|
|
67
79
|
/**
|
|
68
80
|
* Updates the debouncer options
|
|
69
81
|
* Returns the new options state
|
|
70
82
|
*/
|
|
71
|
-
setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn
|
|
83
|
+
setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void;
|
|
72
84
|
/**
|
|
73
85
|
* Returns the current debouncer options
|
|
74
86
|
*/
|
|
75
|
-
getOptions(): Required<AsyncDebouncerOptions<TFn
|
|
87
|
+
getOptions(): Required<AsyncDebouncerOptions<TFn>>;
|
|
76
88
|
/**
|
|
77
89
|
* Attempts to execute the debounced function
|
|
78
90
|
* If a call is already in progress, it will be queued
|
|
79
91
|
*/
|
|
80
|
-
maybeExecute(...args:
|
|
92
|
+
maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
|
|
81
93
|
private executeFunction;
|
|
82
94
|
/**
|
|
83
|
-
*
|
|
95
|
+
* Cancel without resetting _canLeadingExecute
|
|
96
|
+
*/
|
|
97
|
+
private _cancel;
|
|
98
|
+
/**
|
|
99
|
+
* Cancels any pending execution or aborts any execution in progress
|
|
84
100
|
*/
|
|
85
101
|
cancel(): void;
|
|
86
102
|
/**
|
|
87
|
-
* Returns the
|
|
103
|
+
* Returns the last result of the debounced function
|
|
104
|
+
*/
|
|
105
|
+
getLastResult(): ReturnType<TFn> | undefined;
|
|
106
|
+
/**
|
|
107
|
+
* Returns the number of times the function has been executed successfully
|
|
108
|
+
*/
|
|
109
|
+
getSuccessCount(): number;
|
|
110
|
+
/**
|
|
111
|
+
* Returns the number of times the function has settled (completed or errored)
|
|
112
|
+
*/
|
|
113
|
+
getSettleCount(): number;
|
|
114
|
+
/**
|
|
115
|
+
* Returns the number of times the function has errored
|
|
88
116
|
*/
|
|
89
|
-
|
|
117
|
+
getErrorCount(): number;
|
|
90
118
|
/**
|
|
91
|
-
* Returns `true` if there is a pending execution
|
|
119
|
+
* Returns `true` if there is a pending execution queued up for trailing execution
|
|
92
120
|
*/
|
|
93
121
|
getIsPending(): boolean;
|
|
122
|
+
/**
|
|
123
|
+
* Returns `true` if there is currently an execution in progress
|
|
124
|
+
*/
|
|
125
|
+
getIsExecuting(): boolean;
|
|
94
126
|
}
|
|
95
127
|
/**
|
|
96
128
|
* Creates an async debounced function that delays execution until after a specified wait time.
|
|
97
129
|
* The debounced function will only execute once the wait period has elapsed without any new calls.
|
|
98
130
|
* If called again during the wait period, the timer resets and a new wait period begins.
|
|
99
131
|
*
|
|
132
|
+
* Unlike the non-async Debouncer, this async version supports returning values from the debounced function,
|
|
133
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
134
|
+
* instead of setting the result on a state variable from within the debounced function.
|
|
135
|
+
*
|
|
100
136
|
* @example
|
|
101
137
|
* ```ts
|
|
102
138
|
* const debounced = asyncDebounce(async (value: string) => {
|
|
103
|
-
* await saveToAPI(value);
|
|
139
|
+
* const result = await saveToAPI(value);
|
|
140
|
+
* return result; // Return value is preserved
|
|
104
141
|
* }, { wait: 1000 });
|
|
105
142
|
*
|
|
106
143
|
* // Will only execute once, 1 second after the last call
|
|
107
|
-
*
|
|
108
|
-
* await debounced("
|
|
109
|
-
* await debounced("third"); // Executes after 1s
|
|
144
|
+
* // Returns the API response directly
|
|
145
|
+
* const result = await debounced("third");
|
|
110
146
|
* ```
|
|
111
147
|
*/
|
|
112
|
-
export declare function asyncDebounce<TFn extends AnyAsyncFunction
|
|
148
|
+
export declare function asyncDebounce<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
|
|
@@ -1,21 +1,26 @@
|
|
|
1
1
|
const defaultOptions = {
|
|
2
2
|
enabled: true,
|
|
3
3
|
leading: false,
|
|
4
|
-
trailing: true,
|
|
5
4
|
onError: () => {
|
|
6
5
|
},
|
|
7
|
-
|
|
6
|
+
onSettled: () => {
|
|
7
|
+
},
|
|
8
|
+
onSuccess: () => {
|
|
8
9
|
},
|
|
10
|
+
trailing: true,
|
|
9
11
|
wait: 0
|
|
10
12
|
};
|
|
11
13
|
class AsyncDebouncer {
|
|
12
14
|
constructor(fn, initialOptions) {
|
|
13
15
|
this.fn = fn;
|
|
14
16
|
this._abortController = null;
|
|
15
|
-
this.
|
|
17
|
+
this._canLeadingExecute = true;
|
|
18
|
+
this._errorCount = 0;
|
|
16
19
|
this._isExecuting = false;
|
|
20
|
+
this._isPending = false;
|
|
21
|
+
this._settleCount = 0;
|
|
22
|
+
this._successCount = 0;
|
|
17
23
|
this._timeoutId = null;
|
|
18
|
-
this._canLeadingExecute = true;
|
|
19
24
|
this._options = {
|
|
20
25
|
...defaultOptions,
|
|
21
26
|
...initialOptions
|
|
@@ -26,11 +31,10 @@ class AsyncDebouncer {
|
|
|
26
31
|
* Returns the new options state
|
|
27
32
|
*/
|
|
28
33
|
setOptions(newOptions) {
|
|
29
|
-
this._options = {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
}
|
|
33
|
-
return this._options;
|
|
34
|
+
this._options = { ...this._options, ...newOptions };
|
|
35
|
+
if (!this._options.enabled) {
|
|
36
|
+
this._isPending = false;
|
|
37
|
+
}
|
|
34
38
|
}
|
|
35
39
|
/**
|
|
36
40
|
* Returns the current debouncer options
|
|
@@ -43,53 +47,50 @@ class AsyncDebouncer {
|
|
|
43
47
|
* If a call is already in progress, it will be queued
|
|
44
48
|
*/
|
|
45
49
|
async maybeExecute(...args) {
|
|
46
|
-
this.
|
|
50
|
+
this._cancel();
|
|
47
51
|
this._lastArgs = args;
|
|
48
52
|
if (this._options.leading && this._canLeadingExecute) {
|
|
49
53
|
this._canLeadingExecute = false;
|
|
50
54
|
await this.executeFunction(...args);
|
|
55
|
+
return this._lastResult;
|
|
56
|
+
}
|
|
57
|
+
if (this._options.trailing) {
|
|
58
|
+
this._isPending = true;
|
|
51
59
|
}
|
|
52
60
|
return new Promise((resolve) => {
|
|
53
61
|
this._timeoutId = setTimeout(async () => {
|
|
54
|
-
if (this.
|
|
55
|
-
|
|
56
|
-
return;
|
|
62
|
+
if (this._options.trailing && this._lastArgs) {
|
|
63
|
+
await this.executeFunction(...this._lastArgs);
|
|
57
64
|
}
|
|
58
65
|
this._canLeadingExecute = true;
|
|
59
|
-
|
|
60
|
-
this._abortController = new AbortController();
|
|
61
|
-
try {
|
|
62
|
-
this._isExecuting = true;
|
|
63
|
-
if (this._lastArgs) {
|
|
64
|
-
await this.executeFunction(...this._lastArgs);
|
|
65
|
-
}
|
|
66
|
-
} catch (error) {
|
|
67
|
-
try {
|
|
68
|
-
this._options.onError(error);
|
|
69
|
-
} catch {
|
|
70
|
-
console.error("Error in error handler", error);
|
|
71
|
-
}
|
|
72
|
-
} finally {
|
|
73
|
-
this._isExecuting = false;
|
|
74
|
-
this._abortController = null;
|
|
75
|
-
resolve();
|
|
76
|
-
}
|
|
77
|
-
} else {
|
|
78
|
-
resolve();
|
|
79
|
-
}
|
|
66
|
+
resolve(this._lastResult);
|
|
80
67
|
}, this._options.wait);
|
|
81
68
|
});
|
|
82
69
|
}
|
|
83
70
|
async executeFunction(...args) {
|
|
84
|
-
if (!this._options.enabled) return;
|
|
85
|
-
this.
|
|
86
|
-
|
|
87
|
-
|
|
71
|
+
if (!this._options.enabled) return void 0;
|
|
72
|
+
this._abortController = new AbortController();
|
|
73
|
+
try {
|
|
74
|
+
this._isExecuting = true;
|
|
75
|
+
this._lastResult = await this.fn(...args);
|
|
76
|
+
this._successCount++;
|
|
77
|
+
this._options.onSuccess(this._lastResult, this);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
this._errorCount++;
|
|
80
|
+
this._options.onError(error, this);
|
|
81
|
+
} finally {
|
|
82
|
+
this._isExecuting = false;
|
|
83
|
+
this._isPending = false;
|
|
84
|
+
this._settleCount++;
|
|
85
|
+
this._abortController = null;
|
|
86
|
+
this._options.onSettled(this);
|
|
87
|
+
}
|
|
88
|
+
return this._lastResult;
|
|
88
89
|
}
|
|
89
90
|
/**
|
|
90
|
-
*
|
|
91
|
+
* Cancel without resetting _canLeadingExecute
|
|
91
92
|
*/
|
|
92
|
-
|
|
93
|
+
_cancel() {
|
|
93
94
|
if (this._timeoutId) {
|
|
94
95
|
clearTimeout(this._timeoutId);
|
|
95
96
|
this._timeoutId = null;
|
|
@@ -99,19 +100,51 @@ class AsyncDebouncer {
|
|
|
99
100
|
this._abortController = null;
|
|
100
101
|
}
|
|
101
102
|
this._lastArgs = void 0;
|
|
103
|
+
this._isPending = false;
|
|
104
|
+
this._isExecuting = false;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Cancels any pending execution or aborts any execution in progress
|
|
108
|
+
*/
|
|
109
|
+
cancel() {
|
|
102
110
|
this._canLeadingExecute = true;
|
|
111
|
+
this._cancel();
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Returns the last result of the debounced function
|
|
115
|
+
*/
|
|
116
|
+
getLastResult() {
|
|
117
|
+
return this._lastResult;
|
|
103
118
|
}
|
|
104
119
|
/**
|
|
105
|
-
* Returns the number of times the function has been executed
|
|
120
|
+
* Returns the number of times the function has been executed successfully
|
|
106
121
|
*/
|
|
107
|
-
|
|
108
|
-
return this.
|
|
122
|
+
getSuccessCount() {
|
|
123
|
+
return this._successCount;
|
|
109
124
|
}
|
|
110
125
|
/**
|
|
111
|
-
* Returns
|
|
126
|
+
* Returns the number of times the function has settled (completed or errored)
|
|
127
|
+
*/
|
|
128
|
+
getSettleCount() {
|
|
129
|
+
return this._settleCount;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Returns the number of times the function has errored
|
|
133
|
+
*/
|
|
134
|
+
getErrorCount() {
|
|
135
|
+
return this._errorCount;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Returns `true` if there is a pending execution queued up for trailing execution
|
|
112
139
|
*/
|
|
113
140
|
getIsPending() {
|
|
114
|
-
return this._options.enabled &&
|
|
141
|
+
return this._options.enabled && this._isPending;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Returns `true` if there is currently an execution in progress
|
|
145
|
+
*/
|
|
146
|
+
getIsExecuting() {
|
|
147
|
+
return this._isExecuting;
|
|
115
148
|
}
|
|
116
149
|
}
|
|
117
150
|
function asyncDebounce(fn, initialOptions) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-debouncer.js","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws\n */\n onError?: (error: unknown) => void\n /**\n * Optional function to call when the debounced function is executed\n */\n onExecute?: (debouncer: AsyncDebouncer<TFn, TArgs>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds to wait after the last call before executing\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions<any, any>> = {\n enabled: true,\n leading: false,\n trailing: true,\n onError: () => {},\n onExecute: () => {},\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * await searchAPI(value);\n * }, { wait: 500 });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * inputElement.addEventListener('input', () => {\n * asyncDebouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class AsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n private _abortController: AbortController | null = null\n private _executionCount = 0\n private _isExecuting = false\n private _lastArgs: TArgs | undefined\n private _options: Required<AsyncDebouncerOptions<TFn, TArgs>>\n private _timeoutId: ReturnType<typeof setTimeout> | null = null\n private _canLeadingExecute = true\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn, TArgs>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<AsyncDebouncerOptions<TFn, TArgs>>,\n ): Required<AsyncDebouncerOptions<TFn, TArgs>> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n return this._options\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<AsyncDebouncerOptions<TFn, TArgs>> {\n return this._options\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n async maybeExecute(...args: TArgs): Promise<void> {\n this.cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n if (this._isExecuting) {\n resolve()\n return\n }\n\n this._canLeadingExecute = true\n // Execute trailing only if enabled\n if (this._options.trailing) {\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n if (this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n } catch (error) {\n try {\n this._options.onError(error)\n } catch {\n console.error('Error in error handler', error)\n }\n } finally {\n this._isExecuting = false\n this._abortController = null\n resolve()\n }\n } else {\n resolve()\n }\n }, this._options.wait)\n })\n }\n\n private async executeFunction(...args: TArgs): Promise<void> {\n if (!this._options.enabled) return\n this._executionCount++\n await this.fn(...args)\n this._options.onExecute(this)\n }\n\n /**\n * Cancels any pending execution\n */\n cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._canLeadingExecute = true\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns `true` if there is a pending execution\n */\n getIsPending(): boolean {\n return (\n this._options.enabled && (this._timeoutId !== null || this._isExecuting)\n )\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * await saveToAPI(value);\n * }, { wait: 1000 });\n *\n * // Will only execute once, 1 second after the last call\n * await debounced(\"first\"); // Cancelled\n * await debounced(\"second\"); // Cancelled\n * await debounced(\"third\"); // Executes after 1s\n * ```\n */\nexport function asyncDebounce<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions<TFn, TArgs>, 'enabled'>) {\n const asyncDebouncer = new AsyncDebouncer(fn, init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mBAEvC,OAAO;AACV,gBAAA;AACG,mBAAA,SAAS,QAAQ,KAAK;AAAA,YAAA,QACrB;AACE,sBAAA,MAAM,0BAA0B,KAAK;AAAA,YAAA;AAAA,UAC/C,UACA;AACA,iBAAK,eAAe;AACpB,iBAAK,mBAAmB;AAChB,oBAAA;AAAA,UAAA;AAAA,QACV,OACK;AACG,kBAAA;AAAA,QAAA;AAAA,MACV,GACC,KAAK,SAAS,IAAI;AAAA,IAAA,CACtB;AAAA,EAAA;AAAA,EAGH,MAAc,mBAAmB,MAA4B;AACvD,QAAA,CAAC,KAAK,SAAS,QAAS;AACvB,SAAA;AACC,UAAA,KAAK,GAAG,GAAG,IAAI;AAChB,SAAA,SAAS,UAAU,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM9B,SAAe;AACb,QAAI,KAAK,YAAY;AACnB,mBAAa,KAAK,UAAU;AAC5B,WAAK,aAAa;AAAA,IAAA;AAEpB,QAAI,KAAK,kBAAkB;AACzB,WAAK,iBAAiB,MAAM;AAC5B,WAAK,mBAAmB;AAAA,IAAA;AAE1B,SAAK,YAAY;AACjB,SAAK,qBAAqB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM5B,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACtB,WACE,KAAK,SAAS,YAAY,KAAK,eAAe,QAAQ,KAAK;AAAA,EAAA;AAGjE;AAmBgB,SAAA,cAGd,IAAS,gBAAoE;AAC7E,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;"}
|
|
1
|
+
{"version":3,"file":"async-debouncer.js","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws\n */\n onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds to wait after the last call before executing\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions<any>> = {\n enabled: true,\n leading: false,\n onError: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * const results = await searchAPI(value);\n * return results; // Return value is preserved\n * }, { wait: 500 });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * // Returns the API response directly\n * const results = await asyncDebouncer.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncDebouncer<TFn extends AnyAsyncFunction> {\n private _abortController: AbortController | null = null\n private _canLeadingExecute = true\n private _errorCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastResult: ReturnType<TFn> | undefined\n private _options: Required<AsyncDebouncerOptions<TFn>>\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<AsyncDebouncerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this._cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n // Handle trailing execution\n if (this._options.trailing) {\n this._isPending = true\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this._options.trailing && this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n\n // Reset state and resolve\n this._canLeadingExecute = true\n resolve(this._lastResult)\n }, this._options.wait)\n })\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError(error, this)\n } finally {\n this._isExecuting = false\n this._isPending = false\n this._settleCount++\n this._abortController = null\n this._options.onSettled(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancel without resetting _canLeadingExecute\n */\n private _cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._isPending = false\n this._isExecuting = false\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n this._canLeadingExecute = true\n this._cancel()\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns `true` if there is a pending execution queued up for trailing execution\n */\n getIsPending(): boolean {\n return this._options.enabled && this._isPending\n }\n\n /**\n * Returns `true` if there is currently an execution in progress\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, { wait: 1000 });\n *\n * // Will only execute once, 1 second after the last call\n * // Returns the API response directly\n * const result = await debounced(\"third\");\n * ```\n */\nexport function asyncDebounce<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: Omit<AsyncDebouncerOptions<TFn>, 'enabled'>,\n) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":"AAwCA,MAAM,iBAAuD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AAK,SAAS,WAAW,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAuBgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;"}
|
|
@@ -9,6 +9,16 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
9
9
|
* Maximum number of concurrent tasks to process
|
|
10
10
|
*/
|
|
11
11
|
concurrency?: number;
|
|
12
|
+
/**
|
|
13
|
+
* Maximum time in milliseconds that an item can stay in the queue
|
|
14
|
+
* If not provided, items will never expire
|
|
15
|
+
*/
|
|
16
|
+
expirationDuration?: number;
|
|
17
|
+
/**
|
|
18
|
+
* Function to determine if an item has expired
|
|
19
|
+
* If provided, this overrides the expirationDuration behavior
|
|
20
|
+
*/
|
|
21
|
+
getIsExpired?: (item: () => Promise<TValue>, addedAt: number) => boolean;
|
|
12
22
|
/**
|
|
13
23
|
* Default position to get items from during processing
|
|
14
24
|
* @default 'front'
|
|
@@ -47,7 +57,11 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
47
57
|
*/
|
|
48
58
|
onReject?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
|
|
49
59
|
/**
|
|
50
|
-
*
|
|
60
|
+
* Callback fired whenever an item expires in the queuer
|
|
61
|
+
*/
|
|
62
|
+
onExpire?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
|
|
63
|
+
/**
|
|
64
|
+
* Whether the queuer should start processing tasks immediately or not.
|
|
51
65
|
*/
|
|
52
66
|
started?: boolean;
|
|
53
67
|
/**
|
|
@@ -65,6 +79,7 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
65
79
|
* - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
|
|
66
80
|
* - Pause/resume task processing
|
|
67
81
|
* - Task cancellation
|
|
82
|
+
* - Item expiration to clear stale items from the queue
|
|
68
83
|
*
|
|
69
84
|
* Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
|
|
70
85
|
* the next pending task is processed if below the concurrency limit.
|
|
@@ -89,7 +104,9 @@ export declare class AsyncQueuer<TValue> {
|
|
|
89
104
|
private _activeItems;
|
|
90
105
|
private _executionCount;
|
|
91
106
|
private _rejectionCount;
|
|
107
|
+
private _expirationCount;
|
|
92
108
|
private _items;
|
|
109
|
+
private _itemTimestamps;
|
|
93
110
|
private _onErrorCallbacks;
|
|
94
111
|
private _onSettledCallbacks;
|
|
95
112
|
private _onSuccessCallbacks;
|
|
@@ -100,7 +117,7 @@ export declare class AsyncQueuer<TValue> {
|
|
|
100
117
|
* Updates the queuer options
|
|
101
118
|
* Returns the new options state
|
|
102
119
|
*/
|
|
103
|
-
setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>):
|
|
120
|
+
setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): void;
|
|
104
121
|
/**
|
|
105
122
|
* Returns the current queuer options
|
|
106
123
|
*/
|
|
@@ -109,6 +126,10 @@ export declare class AsyncQueuer<TValue> {
|
|
|
109
126
|
* Processes items in the queuer
|
|
110
127
|
*/
|
|
111
128
|
private tick;
|
|
129
|
+
/**
|
|
130
|
+
* Checks for and removes expired items from the queuer
|
|
131
|
+
*/
|
|
132
|
+
private checkExpiredItems;
|
|
112
133
|
/**
|
|
113
134
|
* Starts the queuer and processes items
|
|
114
135
|
*/
|
|
@@ -191,6 +212,10 @@ export declare class AsyncQueuer<TValue> {
|
|
|
191
212
|
* Adds a callback to be called when a task is settled
|
|
192
213
|
*/
|
|
193
214
|
onSettled(cb: (result: TValue | Error) => void): () => void;
|
|
215
|
+
/**
|
|
216
|
+
* Returns the number of items that have expired from the queuer
|
|
217
|
+
*/
|
|
218
|
+
getExpirationCount(): number;
|
|
194
219
|
}
|
|
195
220
|
/**
|
|
196
221
|
* Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
|
|
@@ -209,6 +234,6 @@ export declare class AsyncQueuer<TValue> {
|
|
|
209
234
|
* @param options - Configuration options for the AsyncQueuer
|
|
210
235
|
* @returns A bound addItem function that can be used to add tasks to the queuer
|
|
211
236
|
*/
|
|
212
|
-
export declare function asyncQueue<TValue>(options?: AsyncQueuerOptions<TValue>): (fn: (() => Promise<TValue>) & {
|
|
237
|
+
export declare function asyncQueue<TValue>(options?: Omit<AsyncQueuerOptions<TValue>, 'started'>): (fn: (() => Promise<TValue>) & {
|
|
213
238
|
priority?: number;
|
|
214
239
|
}, position?: QueuePosition, runOnUpdate?: boolean) => Promise<TValue>;
|