@tanstack/pacer 0.1.0 → 0.3.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 +112 -63
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +66 -25
- package/dist/cjs/async-queuer.cjs +198 -124
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +91 -49
- package/dist/cjs/async-rate-limiter.cjs +83 -55
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +55 -28
- package/dist/cjs/async-throttler.cjs +121 -70
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +75 -25
- package/dist/cjs/debouncer.cjs +45 -23
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +27 -12
- package/dist/cjs/index.cjs +2 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +2 -0
- package/dist/cjs/queuer.cjs +161 -101
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +80 -38
- package/dist/cjs/rate-limiter.cjs +52 -44
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +38 -46
- package/dist/cjs/throttler.cjs +57 -44
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +35 -23
- package/dist/cjs/types.d.cts +8 -0
- package/dist/cjs/utils.cjs +13 -0
- package/dist/cjs/utils.cjs.map +1 -0
- package/dist/cjs/utils.d.cts +1 -0
- package/dist/esm/async-debouncer.d.ts +66 -25
- package/dist/esm/async-debouncer.js +112 -63
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +91 -49
- package/dist/esm/async-queuer.js +198 -124
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +55 -28
- package/dist/esm/async-rate-limiter.js +83 -55
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +75 -25
- package/dist/esm/async-throttler.js +121 -70
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/debouncer.d.ts +27 -12
- package/dist/esm/debouncer.js +45 -23
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/queuer.d.ts +80 -38
- package/dist/esm/queuer.js +161 -101
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +38 -46
- package/dist/esm/rate-limiter.js +52 -44
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +35 -23
- package/dist/esm/throttler.js +57 -44
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/types.d.ts +8 -0
- package/dist/esm/utils.d.ts +1 -0
- package/dist/esm/utils.js +13 -0
- package/dist/esm/utils.js.map +1 -0
- package/package.json +8 -1
- package/src/async-debouncer.ts +157 -88
- package/src/async-queuer.ts +266 -148
- package/src/async-rate-limiter.ts +123 -83
- package/src/async-throttler.ts +173 -89
- package/src/debouncer.ts +71 -42
- package/src/index.ts +2 -0
- package/src/queuer.ts +219 -114
- package/src/rate-limiter.ts +74 -88
- package/src/throttler.ts +83 -65
- package/src/types.ts +9 -0
- package/src/utils.ts +13 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
function bindInstanceMethods(instance) {
|
|
4
|
+
return Object.getOwnPropertyNames(Object.getPrototypeOf(instance)).filter((key) => typeof instance[key] === "function").reduce((acc, key) => {
|
|
5
|
+
const method = instance[key];
|
|
6
|
+
if (typeof method === "function") {
|
|
7
|
+
acc[key] = method.bind(instance);
|
|
8
|
+
}
|
|
9
|
+
return acc;
|
|
10
|
+
}, {});
|
|
11
|
+
}
|
|
12
|
+
exports.bindInstanceMethods = bindInstanceMethods;
|
|
13
|
+
//# sourceMappingURL=utils.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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;;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function bindInstanceMethods<T extends Record<string, any>>(instance: T): T;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { AnyAsyncFunction } from './types.js';
|
|
1
2
|
/**
|
|
2
3
|
* Options for configuring an async debounced function
|
|
3
4
|
*/
|
|
4
|
-
export interface AsyncDebouncerOptions {
|
|
5
|
+
export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
5
6
|
/**
|
|
6
7
|
* Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
7
8
|
* Defaults to true.
|
|
@@ -12,6 +13,18 @@ export interface AsyncDebouncerOptions {
|
|
|
12
13
|
* Defaults to false.
|
|
13
14
|
*/
|
|
14
15
|
leading?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Optional error handler for when the debounced function throws
|
|
18
|
+
*/
|
|
19
|
+
onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void;
|
|
20
|
+
/**
|
|
21
|
+
* Optional callback to call when the debounced function is executed
|
|
22
|
+
*/
|
|
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;
|
|
15
28
|
/**
|
|
16
29
|
* Whether to execute on the trailing edge of the timeout.
|
|
17
30
|
* Defaults to true.
|
|
@@ -22,10 +35,6 @@ export interface AsyncDebouncerOptions {
|
|
|
22
35
|
* Defaults to 0ms
|
|
23
36
|
*/
|
|
24
37
|
wait: number;
|
|
25
|
-
/**
|
|
26
|
-
* Optional error handler for when the debounced function throws
|
|
27
|
-
*/
|
|
28
|
-
onError?: (error: unknown) => void;
|
|
29
38
|
}
|
|
30
39
|
/**
|
|
31
40
|
* A class that creates an async debounced function.
|
|
@@ -39,45 +48,77 @@ export interface AsyncDebouncerOptions {
|
|
|
39
48
|
*
|
|
40
49
|
* @example
|
|
41
50
|
* ```ts
|
|
42
|
-
* const
|
|
51
|
+
* const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
|
|
43
52
|
* await searchAPI(value);
|
|
44
53
|
* }, { wait: 500 });
|
|
45
54
|
*
|
|
46
55
|
* // Called on each keystroke but only executes after 500ms of no typing
|
|
47
56
|
* inputElement.addEventListener('input', () => {
|
|
48
|
-
*
|
|
57
|
+
* asyncDebouncer.maybeExecute(inputElement.value);
|
|
49
58
|
* });
|
|
50
59
|
* ```
|
|
51
60
|
*/
|
|
52
|
-
export declare class AsyncDebouncer<TFn extends
|
|
61
|
+
export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
53
62
|
private fn;
|
|
54
|
-
private
|
|
55
|
-
private
|
|
56
|
-
private
|
|
57
|
-
private
|
|
58
|
-
private
|
|
59
|
-
private
|
|
60
|
-
private
|
|
61
|
-
|
|
63
|
+
private _abortController;
|
|
64
|
+
private _canLeadingExecute;
|
|
65
|
+
private _errorCount;
|
|
66
|
+
private _isExecuting;
|
|
67
|
+
private _isPending;
|
|
68
|
+
private _lastArgs;
|
|
69
|
+
private _lastResult;
|
|
70
|
+
private _options;
|
|
71
|
+
private _settleCount;
|
|
72
|
+
private _successCount;
|
|
73
|
+
private _timeoutId;
|
|
74
|
+
constructor(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>);
|
|
62
75
|
/**
|
|
63
76
|
* Updates the debouncer options
|
|
64
77
|
* Returns the new options state
|
|
65
78
|
*/
|
|
66
|
-
setOptions(newOptions: Partial<AsyncDebouncerOptions
|
|
79
|
+
setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void;
|
|
67
80
|
/**
|
|
68
|
-
* Returns the
|
|
81
|
+
* Returns the current debouncer options
|
|
69
82
|
*/
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Cancels any pending execution
|
|
73
|
-
*/
|
|
74
|
-
cancel(): void;
|
|
83
|
+
getOptions(): Required<AsyncDebouncerOptions<TFn>>;
|
|
75
84
|
/**
|
|
76
85
|
* Attempts to execute the debounced function
|
|
77
86
|
* If a call is already in progress, it will be queued
|
|
78
87
|
*/
|
|
79
|
-
maybeExecute(...args:
|
|
88
|
+
maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
|
|
80
89
|
private executeFunction;
|
|
90
|
+
/**
|
|
91
|
+
* Cancel without resetting _canLeadingExecute
|
|
92
|
+
*/
|
|
93
|
+
private _cancel;
|
|
94
|
+
/**
|
|
95
|
+
* Cancels any pending execution or aborts any execution in progress
|
|
96
|
+
*/
|
|
97
|
+
cancel(): void;
|
|
98
|
+
/**
|
|
99
|
+
* Returns the last result of the debounced function
|
|
100
|
+
*/
|
|
101
|
+
getLastResult(): ReturnType<TFn> | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* Returns the number of times the function has been executed successfully
|
|
104
|
+
*/
|
|
105
|
+
getSuccessCount(): number;
|
|
106
|
+
/**
|
|
107
|
+
* Returns the number of times the function has settled (completed or errored)
|
|
108
|
+
*/
|
|
109
|
+
getSettleCount(): number;
|
|
110
|
+
/**
|
|
111
|
+
* Returns the number of times the function has errored
|
|
112
|
+
*/
|
|
113
|
+
getErrorCount(): number;
|
|
114
|
+
/**
|
|
115
|
+
* Returns `true` if there is a pending execution queued up for trailing execution
|
|
116
|
+
*/
|
|
117
|
+
getIsPending(): boolean;
|
|
118
|
+
/**
|
|
119
|
+
* Returns `true` if there is currently an execution in progress
|
|
120
|
+
*/
|
|
121
|
+
getIsExecuting(): boolean;
|
|
81
122
|
}
|
|
82
123
|
/**
|
|
83
124
|
* Creates an async debounced function that delays execution until after a specified wait time.
|
|
@@ -96,4 +137,4 @@ export declare class AsyncDebouncer<TFn extends (...args: Array<any>) => Promise
|
|
|
96
137
|
* await debounced("third"); // Executes after 1s
|
|
97
138
|
* ```
|
|
98
139
|
*/
|
|
99
|
-
export declare function asyncDebounce<TFn extends
|
|
140
|
+
export declare function asyncDebounce<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
|
|
@@ -1,20 +1,27 @@
|
|
|
1
1
|
const defaultOptions = {
|
|
2
2
|
enabled: true,
|
|
3
3
|
leading: false,
|
|
4
|
-
trailing: true,
|
|
5
4
|
onError: () => {
|
|
6
5
|
},
|
|
6
|
+
onSettled: () => {
|
|
7
|
+
},
|
|
8
|
+
onSuccess: () => {
|
|
9
|
+
},
|
|
10
|
+
trailing: true,
|
|
7
11
|
wait: 0
|
|
8
12
|
};
|
|
9
13
|
class AsyncDebouncer {
|
|
10
14
|
constructor(fn, initialOptions) {
|
|
11
15
|
this.fn = fn;
|
|
12
|
-
this.
|
|
13
|
-
this.
|
|
14
|
-
this.
|
|
15
|
-
this.
|
|
16
|
-
this.
|
|
17
|
-
this.
|
|
16
|
+
this._abortController = null;
|
|
17
|
+
this._canLeadingExecute = true;
|
|
18
|
+
this._errorCount = 0;
|
|
19
|
+
this._isExecuting = false;
|
|
20
|
+
this._isPending = false;
|
|
21
|
+
this._settleCount = 0;
|
|
22
|
+
this._successCount = 0;
|
|
23
|
+
this._timeoutId = null;
|
|
24
|
+
this._options = {
|
|
18
25
|
...defaultOptions,
|
|
19
26
|
...initialOptions
|
|
20
27
|
};
|
|
@@ -24,78 +31,120 @@ class AsyncDebouncer {
|
|
|
24
31
|
* Returns the new options state
|
|
25
32
|
*/
|
|
26
33
|
setOptions(newOptions) {
|
|
27
|
-
this.
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
return this.options;
|
|
34
|
+
this._options = { ...this._options, ...newOptions };
|
|
35
|
+
if (!this._options.enabled) {
|
|
36
|
+
this._isPending = false;
|
|
37
|
+
}
|
|
32
38
|
}
|
|
33
39
|
/**
|
|
34
|
-
* Returns the
|
|
40
|
+
* Returns the current debouncer options
|
|
35
41
|
*/
|
|
36
|
-
|
|
37
|
-
return this.
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Cancels any pending execution
|
|
41
|
-
*/
|
|
42
|
-
cancel() {
|
|
43
|
-
if (this.timeoutId) {
|
|
44
|
-
clearTimeout(this.timeoutId);
|
|
45
|
-
this.timeoutId = null;
|
|
46
|
-
}
|
|
47
|
-
if (this.abortController) {
|
|
48
|
-
this.abortController.abort();
|
|
49
|
-
this.abortController = null;
|
|
50
|
-
}
|
|
51
|
-
this.lastArgs = void 0;
|
|
52
|
-
this.canLeadingExecute = true;
|
|
42
|
+
getOptions() {
|
|
43
|
+
return this._options;
|
|
53
44
|
}
|
|
54
45
|
/**
|
|
55
46
|
* Attempts to execute the debounced function
|
|
56
47
|
* If a call is already in progress, it will be queued
|
|
57
48
|
*/
|
|
58
49
|
async maybeExecute(...args) {
|
|
59
|
-
this.
|
|
60
|
-
this.
|
|
61
|
-
if (this.
|
|
62
|
-
this.
|
|
50
|
+
this._cancel();
|
|
51
|
+
this._lastArgs = args;
|
|
52
|
+
if (this._options.leading && this._canLeadingExecute) {
|
|
53
|
+
this._canLeadingExecute = false;
|
|
63
54
|
await this.executeFunction(...args);
|
|
55
|
+
return this._lastResult;
|
|
56
|
+
}
|
|
57
|
+
if (this._options.trailing) {
|
|
58
|
+
this._isPending = true;
|
|
64
59
|
}
|
|
65
60
|
return new Promise((resolve) => {
|
|
66
|
-
this.
|
|
67
|
-
if (this.
|
|
68
|
-
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
this.canLeadingExecute = true;
|
|
72
|
-
if (this.options.trailing) {
|
|
73
|
-
this.abortController = new AbortController();
|
|
74
|
-
try {
|
|
75
|
-
this.isExecuting = true;
|
|
76
|
-
if (this.lastArgs) {
|
|
77
|
-
await this.executeFunction(...this.lastArgs);
|
|
78
|
-
}
|
|
79
|
-
} catch (error) {
|
|
80
|
-
try {
|
|
81
|
-
this.options.onError(error);
|
|
82
|
-
} catch {
|
|
83
|
-
}
|
|
84
|
-
} finally {
|
|
85
|
-
this.isExecuting = false;
|
|
86
|
-
this.abortController = null;
|
|
87
|
-
resolve();
|
|
88
|
-
}
|
|
89
|
-
} else {
|
|
90
|
-
resolve();
|
|
61
|
+
this._timeoutId = setTimeout(async () => {
|
|
62
|
+
if (this._options.trailing && this._lastArgs) {
|
|
63
|
+
await this.executeFunction(...this._lastArgs);
|
|
91
64
|
}
|
|
92
|
-
|
|
65
|
+
this._canLeadingExecute = true;
|
|
66
|
+
resolve(this._lastResult);
|
|
67
|
+
}, this._options.wait);
|
|
93
68
|
});
|
|
94
69
|
}
|
|
95
70
|
async executeFunction(...args) {
|
|
96
|
-
if (!this.
|
|
97
|
-
this.
|
|
98
|
-
|
|
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;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Cancel without resetting _canLeadingExecute
|
|
92
|
+
*/
|
|
93
|
+
_cancel() {
|
|
94
|
+
if (this._timeoutId) {
|
|
95
|
+
clearTimeout(this._timeoutId);
|
|
96
|
+
this._timeoutId = null;
|
|
97
|
+
}
|
|
98
|
+
if (this._abortController) {
|
|
99
|
+
this._abortController.abort();
|
|
100
|
+
this._abortController = null;
|
|
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() {
|
|
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;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Returns the number of times the function has been executed successfully
|
|
121
|
+
*/
|
|
122
|
+
getSuccessCount() {
|
|
123
|
+
return this._successCount;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
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
|
|
139
|
+
*/
|
|
140
|
+
getIsPending() {
|
|
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;
|
|
99
148
|
}
|
|
100
149
|
}
|
|
101
150
|
function asyncDebounce(fn, initialOptions) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-debouncer.js","sources":["../../src/async-debouncer.ts"],"sourcesContent":["/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions {\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 * 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 * Optional error handler for when the debounced function throws\n */\n onError?: (error: unknown) => void\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions> = {\n enabled: true,\n leading: false,\n trailing: true,\n onError: () => {},\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 debouncer = 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 * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class AsyncDebouncer<\n TFn extends (...args: Array<any>) => Promise<any>,\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>\n private timeoutId: ReturnType<typeof setTimeout> | null = null\n private canLeadingExecute = true\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions,\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>,\n ): Required<AsyncDebouncerOptions> {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\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 * 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 * 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 // Ignore errors from error handler\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 }\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 (...args: Array<any>) => Promise<any>,\n>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions, 'enabled'>) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":"AA8BA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,MAAM;AACR;AAwBO,MAAM,eAGX;AAAA,EASA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,kBAA0C;AAClD,SAAQ,iBAAiB;AACzB,SAAQ,cAAc;AAGtB,SAAQ,YAAkD;AAC1D,SAAQ,oBAAoB;AAM1B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YACiC;AACjC,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,SAAe;AACb,QAAI,KAAK,WAAW;AAClB,mBAAa,KAAK,SAAS;AAC3B,WAAK,YAAY;AAAA,IAAA;AAEnB,QAAI,KAAK,iBAAiB;AACxB,WAAK,gBAAgB,MAAM;AAC3B,WAAK,kBAAkB;AAAA,IAAA;AAEzB,SAAK,WAAW;AAChB,SAAK,oBAAoB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO3B,MAAM,gBAAgB,MAA4B;AAChD,SAAK,OAAO;AACZ,SAAK,WAAW;AAGhB,QAAI,KAAK,QAAQ,WAAW,KAAK,mBAAmB;AAClD,WAAK,oBAAoB;AACnB,YAAA,KAAK,gBAAgB,GAAG,IAAI;AAAA,IAAA;AAG7B,WAAA,IAAI,QAAQ,CAAC,YAAY;AACzB,WAAA,YAAY,WAAW,YAAY;AACtC,YAAI,KAAK,aAAa;AACZ,kBAAA;AACR;AAAA,QAAA;AAGF,aAAK,oBAAoB;AAErB,YAAA,KAAK,QAAQ,UAAU;AACpB,eAAA,kBAAkB,IAAI,gBAAgB;AACvC,cAAA;AACF,iBAAK,cAAc;AACnB,gBAAI,KAAK,UAAU;AACjB,oBAAM,KAAK,gBAAgB,GAAG,KAAK,QAAQ;AAAA,YAAA;AAAA,mBAEtC,OAAO;AACV,gBAAA;AACG,mBAAA,QAAQ,QAAQ,KAAK;AAAA,YAAA,QACpB;AAAA,YAAA;AAAA,UAER,UACA;AACA,iBAAK,cAAc;AACnB,iBAAK,kBAAkB;AACf,oBAAA;AAAA,UAAA;AAAA,QACV,OACK;AACG,kBAAA;AAAA,QAAA;AAAA,MACV,GACC,KAAK,QAAQ,IAAI;AAAA,IAAA,CACrB;AAAA,EAAA;AAAA,EAGH,MAAc,mBAAmB,MAA4B;AACvD,QAAA,CAAC,KAAK,QAAQ,QAAS;AACtB,SAAA;AACC,UAAA,KAAK,GAAG,GAAG,IAAI;AAAA,EAAA;AAEzB;AAmBgB,SAAA,cAEd,IAAS,gBAAwD;AACjE,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 * @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<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 * @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<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;AAAA,EAC3D,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AAwBO,MAAM,eAA6C;AAAA,EAaxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAbV,SAAQ,mBAA2C;AACnD,SAAQ,qBAAqB;AAC7B,SAAQ,cAAc;AACtB,SAAQ,eAAe;AACvB,SAAQ,aAAa;AAIrB,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,aAAoC;AAM1C,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAuD;AAChE,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAG9C,QAAA,CAAC,KAAK,SAAS,SAAS;AAC1B,WAAK,aAAa;AAAA,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAMF,aAAmD;AACjD,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,MAAM,gBACD,MACmC;AACtC,SAAK,QAAQ;AACb,SAAK,YAAY;AAGjB,QAAI,KAAK,SAAS,WAAW,KAAK,oBAAoB;AACpD,WAAK,qBAAqB;AACpB,YAAA,KAAK,gBAAgB,GAAG,IAAI;AAClC,aAAO,KAAK;AAAA,IAAA;AAIV,QAAA,KAAK,SAAS,UAAU;AAC1B,WAAK,aAAa;AAAA,IAAA;AAGb,WAAA,IAAI,QAAQ,CAAC,YAAY;AACzB,WAAA,aAAa,WAAW,YAAY;AAEvC,YAAI,KAAK,SAAS,YAAY,KAAK,WAAW;AAC5C,gBAAM,KAAK,gBAAgB,GAAG,KAAK,SAAS;AAAA,QAAA;AAI9C,aAAK,qBAAqB;AAC1B,gBAAQ,KAAK,WAAW;AAAA,MAAA,GACvB,KAAK,SAAS,IAAI;AAAA,IAAA,CACtB;AAAA,EAAA;AAAA,EAGH,MAAc,mBACT,MACmC;AACtC,QAAI,CAAC,KAAK,SAAS,QAAgB,QAAA;AAC9B,SAAA,mBAAmB,IAAI,gBAAgB;AACxC,QAAA;AACF,WAAK,eAAe;AACpB,WAAK,cAAc,MAAM,KAAK,GAAG,GAAG,IAAI;AACnC,WAAA;AACL,WAAK,SAAS,UAAU,KAAK,aAAc,IAAI;AAAA,aACxC,OAAO;AACT,WAAA;AACA,WAAA,SAAS,QAAQ,OAAO,IAAI;AAAA,IAAA,UACjC;AACA,WAAK,eAAe;AACpB,WAAK,aAAa;AACb,WAAA;AACL,WAAK,mBAAmB;AACnB,WAAA,SAAS,UAAU,IAAI;AAAA,IAAA;AAE9B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMN,UAAgB;AACtB,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,aAAa;AAClB,SAAK,eAAe;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMtB,SAAe;AACb,SAAK,qBAAqB;AAC1B,SAAK,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMf,gBAA6C;AAC3C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,SAAS,WAAW,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAmBgB,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'
|
|
@@ -34,12 +44,24 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
34
44
|
* Callback fired whenever an item is removed from the queuer
|
|
35
45
|
*/
|
|
36
46
|
onGetNextItem?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
|
|
47
|
+
/**
|
|
48
|
+
* Callback fired whenever the queuer's running state changes
|
|
49
|
+
*/
|
|
50
|
+
onIsRunningChange?: (queuer: AsyncQueuer<TValue>) => void;
|
|
37
51
|
/**
|
|
38
52
|
* Callback fired whenever an item is added or removed from the queuer
|
|
39
53
|
*/
|
|
40
|
-
|
|
54
|
+
onItemsChange?: (queuer: AsyncQueuer<TValue>) => void;
|
|
55
|
+
/**
|
|
56
|
+
* Callback fired whenever an item is rejected from being added to the queuer
|
|
57
|
+
*/
|
|
58
|
+
onReject?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
|
|
41
59
|
/**
|
|
42
|
-
*
|
|
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.
|
|
43
65
|
*/
|
|
44
66
|
started?: boolean;
|
|
45
67
|
/**
|
|
@@ -48,54 +70,82 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
48
70
|
wait?: number;
|
|
49
71
|
}
|
|
50
72
|
/**
|
|
51
|
-
* A flexible asynchronous
|
|
73
|
+
* A flexible asynchronous queue that processes tasks with configurable concurrency control.
|
|
52
74
|
*
|
|
53
75
|
* Features:
|
|
54
|
-
* - Priority
|
|
76
|
+
* - Priority queue support via getPriority option
|
|
55
77
|
* - Configurable concurrency limit
|
|
56
78
|
* - Task success/error/completion callbacks
|
|
57
|
-
* - FIFO (First In First Out) or LIFO (Last In First Out)
|
|
79
|
+
* - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
|
|
58
80
|
* - Pause/resume task processing
|
|
59
81
|
* - Task cancellation
|
|
82
|
+
* - Item expiration to clear stale items from the queue
|
|
60
83
|
*
|
|
61
84
|
* Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
|
|
62
85
|
* the next pending task is processed if below the concurrency limit.
|
|
63
86
|
*
|
|
64
87
|
* @example
|
|
65
88
|
* ```ts
|
|
66
|
-
* const
|
|
89
|
+
* const asyncQueuer = new AsyncQueuer<string>({ concurrency: 2 });
|
|
67
90
|
*
|
|
68
|
-
*
|
|
91
|
+
* asyncQueuer.addItem(async () => {
|
|
69
92
|
* return 'Hello';
|
|
70
93
|
* });
|
|
71
94
|
*
|
|
72
|
-
*
|
|
95
|
+
* asyncQueuer.start();
|
|
73
96
|
*
|
|
74
|
-
*
|
|
97
|
+
* asyncQueuer.onSuccess((result) => {
|
|
75
98
|
* console.log(result); // 'Hello'
|
|
76
99
|
* });
|
|
77
100
|
* ```
|
|
78
101
|
*/
|
|
79
102
|
export declare class AsyncQueuer<TValue> {
|
|
80
|
-
|
|
81
|
-
private
|
|
82
|
-
private
|
|
83
|
-
private
|
|
84
|
-
private
|
|
85
|
-
private
|
|
86
|
-
private
|
|
87
|
-
private
|
|
88
|
-
private
|
|
103
|
+
private _options;
|
|
104
|
+
private _activeItems;
|
|
105
|
+
private _executionCount;
|
|
106
|
+
private _rejectionCount;
|
|
107
|
+
private _expirationCount;
|
|
108
|
+
private _items;
|
|
109
|
+
private _itemTimestamps;
|
|
110
|
+
private _onErrorCallbacks;
|
|
111
|
+
private _onSettledCallbacks;
|
|
112
|
+
private _onSuccessCallbacks;
|
|
113
|
+
private _pendingTick;
|
|
114
|
+
private _running;
|
|
89
115
|
constructor(initialOptions?: AsyncQueuerOptions<TValue>);
|
|
90
116
|
/**
|
|
91
117
|
* Updates the queuer options
|
|
92
118
|
* Returns the new options state
|
|
93
119
|
*/
|
|
94
|
-
setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>):
|
|
120
|
+
setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): void;
|
|
121
|
+
/**
|
|
122
|
+
* Returns the current queuer options
|
|
123
|
+
*/
|
|
124
|
+
getOptions(): Required<AsyncQueuerOptions<TValue>>;
|
|
95
125
|
/**
|
|
96
126
|
* Processes items in the queuer
|
|
97
127
|
*/
|
|
98
|
-
|
|
128
|
+
private tick;
|
|
129
|
+
/**
|
|
130
|
+
* Checks for and removes expired items from the queuer
|
|
131
|
+
*/
|
|
132
|
+
private checkExpiredItems;
|
|
133
|
+
/**
|
|
134
|
+
* Starts the queuer and processes items
|
|
135
|
+
*/
|
|
136
|
+
start(): Promise<void>;
|
|
137
|
+
/**
|
|
138
|
+
* Stops the queuer from processing items
|
|
139
|
+
*/
|
|
140
|
+
stop(): void;
|
|
141
|
+
/**
|
|
142
|
+
* Removes all items from the queuer
|
|
143
|
+
*/
|
|
144
|
+
clear(): void;
|
|
145
|
+
/**
|
|
146
|
+
* Resets the queuer to its initial state
|
|
147
|
+
*/
|
|
148
|
+
reset(withInitialItems?: boolean): void;
|
|
99
149
|
/**
|
|
100
150
|
* Adds a task to the queuer
|
|
101
151
|
*/
|
|
@@ -109,43 +159,47 @@ export declare class AsyncQueuer<TValue> {
|
|
|
109
159
|
/**
|
|
110
160
|
* Returns an item without removing it
|
|
111
161
|
*/
|
|
112
|
-
|
|
162
|
+
getPeek(position?: QueuePosition): (() => Promise<TValue>) | undefined;
|
|
113
163
|
/**
|
|
114
164
|
* Returns true if the queuer is empty
|
|
115
165
|
*/
|
|
116
|
-
|
|
166
|
+
getIsEmpty(): boolean;
|
|
117
167
|
/**
|
|
118
168
|
* Returns true if the queuer is full
|
|
119
169
|
*/
|
|
120
|
-
|
|
170
|
+
getIsFull(): boolean;
|
|
121
171
|
/**
|
|
122
172
|
* Returns the current size of the queuer
|
|
123
173
|
*/
|
|
124
|
-
|
|
174
|
+
getSize(): number;
|
|
125
175
|
/**
|
|
126
|
-
*
|
|
176
|
+
* Returns a copy of all items in the queuer
|
|
127
177
|
*/
|
|
128
|
-
|
|
178
|
+
getAllItems(): Array<() => Promise<TValue>>;
|
|
129
179
|
/**
|
|
130
|
-
*
|
|
180
|
+
* Returns the active items
|
|
131
181
|
*/
|
|
132
|
-
|
|
182
|
+
getActiveItems(): Array<() => Promise<TValue>>;
|
|
133
183
|
/**
|
|
134
|
-
* Returns
|
|
184
|
+
* Returns the pending items
|
|
135
185
|
*/
|
|
136
|
-
|
|
186
|
+
getPendingItems(): Array<() => Promise<TValue>>;
|
|
137
187
|
/**
|
|
138
188
|
* Returns the number of items that have been removed from the queuer
|
|
139
189
|
*/
|
|
140
190
|
getExecutionCount(): number;
|
|
141
191
|
/**
|
|
142
|
-
* Returns the
|
|
192
|
+
* Returns the number of items that have been rejected from the queuer
|
|
143
193
|
*/
|
|
144
|
-
|
|
194
|
+
getRejectionCount(): number;
|
|
145
195
|
/**
|
|
146
|
-
* Returns the
|
|
196
|
+
* Returns true if the queuer is running
|
|
147
197
|
*/
|
|
148
|
-
|
|
198
|
+
getIsRunning(): boolean;
|
|
199
|
+
/**
|
|
200
|
+
* Returns true if the queuer is running but has no items to process
|
|
201
|
+
*/
|
|
202
|
+
getIsIdle(): boolean;
|
|
149
203
|
/**
|
|
150
204
|
* Adds a callback to be called when a task succeeds
|
|
151
205
|
*/
|
|
@@ -159,21 +213,9 @@ export declare class AsyncQueuer<TValue> {
|
|
|
159
213
|
*/
|
|
160
214
|
onSettled(cb: (result: TValue | Error) => void): () => void;
|
|
161
215
|
/**
|
|
162
|
-
*
|
|
163
|
-
*/
|
|
164
|
-
start(): Promise<void>;
|
|
165
|
-
/**
|
|
166
|
-
* Stops the queuer from processing items
|
|
167
|
-
*/
|
|
168
|
-
stop(): void;
|
|
169
|
-
/**
|
|
170
|
-
* Returns true if the queuer is running
|
|
171
|
-
*/
|
|
172
|
-
isRunning(): boolean;
|
|
173
|
-
/**
|
|
174
|
-
* Returns true if the queuer is running but has no items to process
|
|
216
|
+
* Returns the number of items that have expired from the queuer
|
|
175
217
|
*/
|
|
176
|
-
|
|
218
|
+
getExpirationCount(): number;
|
|
177
219
|
}
|
|
178
220
|
/**
|
|
179
221
|
* Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
|
|
@@ -192,6 +234,6 @@ export declare class AsyncQueuer<TValue> {
|
|
|
192
234
|
* @param options - Configuration options for the AsyncQueuer
|
|
193
235
|
* @returns A bound addItem function that can be used to add tasks to the queuer
|
|
194
236
|
*/
|
|
195
|
-
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>) & {
|
|
196
238
|
priority?: number;
|
|
197
239
|
}, position?: QueuePosition, runOnUpdate?: boolean) => Promise<TValue>;
|