@tanstack/pacer 0.1.0 → 0.2.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 +60 -44
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +37 -24
- package/dist/cjs/async-queuer.cjs +149 -125
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +65 -48
- package/dist/cjs/async-rate-limiter.cjs +63 -46
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +39 -27
- package/dist/cjs/async-throttler.cjs +70 -47
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +43 -25
- package/dist/cjs/debouncer.cjs +46 -22
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +25 -11
- 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 +114 -104
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +53 -40
- package/dist/cjs/rate-limiter.cjs +54 -42
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +37 -45
- package/dist/cjs/throttler.cjs +61 -41
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +35 -22
- package/dist/cjs/types.d.cts +12 -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 +37 -24
- package/dist/esm/async-debouncer.js +60 -44
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +65 -48
- package/dist/esm/async-queuer.js +149 -125
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +39 -27
- package/dist/esm/async-rate-limiter.js +63 -46
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +43 -25
- package/dist/esm/async-throttler.js +70 -47
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/debouncer.d.ts +25 -11
- package/dist/esm/debouncer.js +46 -22
- 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 +53 -40
- package/dist/esm/queuer.js +114 -104
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +37 -45
- package/dist/esm/rate-limiter.js +54 -42
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +35 -22
- package/dist/esm/throttler.js +61 -41
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/types.d.ts +12 -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 +90 -62
- package/src/async-queuer.ts +178 -145
- package/src/async-rate-limiter.ts +93 -67
- package/src/async-throttler.ts +98 -63
- package/src/debouncer.ts +71 -35
- package/src/index.ts +2 -0
- package/src/queuer.ts +135 -118
- package/src/rate-limiter.ts +79 -81
- package/src/throttler.ts +87 -61
- package/src/types.ts +17 -0
- package/src/utils.ts +13 -0
|
@@ -1,11 +1,20 @@
|
|
|
1
|
+
const defaultOptions = {
|
|
2
|
+
enabled: true,
|
|
3
|
+
onReject: () => {
|
|
4
|
+
},
|
|
5
|
+
onError: () => {
|
|
6
|
+
},
|
|
7
|
+
onExecute: () => {
|
|
8
|
+
}
|
|
9
|
+
};
|
|
1
10
|
class AsyncRateLimiter {
|
|
2
11
|
constructor(fn, initialOptions) {
|
|
3
12
|
this.fn = fn;
|
|
4
|
-
this.
|
|
5
|
-
this.
|
|
6
|
-
this.
|
|
7
|
-
this.
|
|
8
|
-
|
|
13
|
+
this._executionCount = 0;
|
|
14
|
+
this._executionTimes = [];
|
|
15
|
+
this._rejectionCount = 0;
|
|
16
|
+
this._options = {
|
|
17
|
+
...defaultOptions,
|
|
9
18
|
...initialOptions
|
|
10
19
|
};
|
|
11
20
|
}
|
|
@@ -14,30 +23,17 @@ class AsyncRateLimiter {
|
|
|
14
23
|
* Returns the new options state
|
|
15
24
|
*/
|
|
16
25
|
setOptions(newOptions) {
|
|
17
|
-
this.
|
|
18
|
-
...this.
|
|
26
|
+
this._options = {
|
|
27
|
+
...this._options,
|
|
19
28
|
...newOptions
|
|
20
29
|
};
|
|
21
|
-
return this.
|
|
30
|
+
return this._options;
|
|
22
31
|
}
|
|
23
32
|
/**
|
|
24
|
-
* Returns the
|
|
33
|
+
* Returns the current rate limiter options
|
|
25
34
|
*/
|
|
26
|
-
|
|
27
|
-
return this.
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Returns the number of times the function has been rejected
|
|
31
|
-
*/
|
|
32
|
-
getRejectionCount() {
|
|
33
|
-
return this.rejectionCount;
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Returns the number of remaining executions allowed in the current window
|
|
37
|
-
*/
|
|
38
|
-
getRemainingInWindow() {
|
|
39
|
-
this.cleanupOldExecutions();
|
|
40
|
-
return Math.max(0, this.options.limit - this.executionTimes.length);
|
|
35
|
+
getOptions() {
|
|
36
|
+
return this._options;
|
|
41
37
|
}
|
|
42
38
|
/**
|
|
43
39
|
* Attempts to execute the rate-limited function if within the configured limits.
|
|
@@ -57,7 +53,7 @@ class AsyncRateLimiter {
|
|
|
57
53
|
*/
|
|
58
54
|
async maybeExecute(...args) {
|
|
59
55
|
this.cleanupOldExecutions();
|
|
60
|
-
if (this.
|
|
56
|
+
if (this._executionTimes.length < this._options.limit) {
|
|
61
57
|
await this.executeFunction(...args);
|
|
62
58
|
return true;
|
|
63
59
|
}
|
|
@@ -65,50 +61,71 @@ class AsyncRateLimiter {
|
|
|
65
61
|
return false;
|
|
66
62
|
}
|
|
67
63
|
async executeFunction(...args) {
|
|
68
|
-
|
|
64
|
+
var _a, _b;
|
|
65
|
+
if (!this._options.enabled) return;
|
|
69
66
|
const now = Date.now();
|
|
70
|
-
this.
|
|
71
|
-
this.
|
|
67
|
+
this._executionCount++;
|
|
68
|
+
this._executionTimes.push(now);
|
|
72
69
|
try {
|
|
73
70
|
await this.fn(...args);
|
|
74
71
|
} catch (error) {
|
|
75
|
-
if (this.
|
|
72
|
+
if (this._options.onError) {
|
|
76
73
|
try {
|
|
77
|
-
this.
|
|
78
|
-
} catch {
|
|
74
|
+
this._options.onError(error);
|
|
75
|
+
} catch (error2) {
|
|
76
|
+
console.error("Error in onError handler", error2);
|
|
79
77
|
}
|
|
80
78
|
}
|
|
81
79
|
throw error;
|
|
82
80
|
} finally {
|
|
81
|
+
(_b = (_a = this._options).onExecute) == null ? void 0 : _b.call(_a, this);
|
|
83
82
|
}
|
|
84
83
|
}
|
|
85
84
|
rejectFunction() {
|
|
86
|
-
this.
|
|
87
|
-
if (this.
|
|
88
|
-
|
|
89
|
-
const msUntilNextWindow = oldestExecution + this.options.window - Date.now();
|
|
90
|
-
this.options.onReject({
|
|
91
|
-
msUntilNextWindow,
|
|
92
|
-
currentExecutions: this.executionTimes.length,
|
|
93
|
-
limit: this.options.limit,
|
|
94
|
-
rejectionCount: this.rejectionCount
|
|
95
|
-
});
|
|
85
|
+
this._rejectionCount++;
|
|
86
|
+
if (this._options.onReject) {
|
|
87
|
+
this._options.onReject(this);
|
|
96
88
|
}
|
|
97
89
|
}
|
|
98
90
|
cleanupOldExecutions() {
|
|
99
91
|
const now = Date.now();
|
|
100
|
-
const windowStart = now - this.
|
|
101
|
-
this.
|
|
92
|
+
const windowStart = now - this._options.window;
|
|
93
|
+
this._executionTimes = this._executionTimes.filter(
|
|
102
94
|
(time) => time > windowStart
|
|
103
95
|
);
|
|
104
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* Returns the number of times the function has been executed
|
|
99
|
+
*/
|
|
100
|
+
getExecutionCount() {
|
|
101
|
+
return this._executionCount;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Returns the number of times the function has been rejected
|
|
105
|
+
*/
|
|
106
|
+
getRejectionCount() {
|
|
107
|
+
return this._rejectionCount;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Returns the number of remaining executions allowed in the current window
|
|
111
|
+
*/
|
|
112
|
+
getRemainingInWindow() {
|
|
113
|
+
this.cleanupOldExecutions();
|
|
114
|
+
return Math.max(0, this._options.limit - this._executionTimes.length);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Returns the number of milliseconds until the next execution will be possible
|
|
118
|
+
*/
|
|
119
|
+
getMsUntilNextWindow() {
|
|
120
|
+
return this.getRemainingInWindow() * this._options.window;
|
|
121
|
+
}
|
|
105
122
|
/**
|
|
106
123
|
* Resets the rate limiter state
|
|
107
124
|
*/
|
|
108
125
|
reset() {
|
|
109
|
-
this.
|
|
110
|
-
this.
|
|
111
|
-
this.
|
|
126
|
+
this._executionTimes = [];
|
|
127
|
+
this._executionCount = 0;
|
|
128
|
+
this._rejectionCount = 0;
|
|
112
129
|
}
|
|
113
130
|
}
|
|
114
131
|
function asyncRateLimit(fn, initialOptions) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-rate-limiter.js","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"async-rate-limiter.js","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Optional error handler for when the rate-limited function throws\n */\n onError?: (error: unknown) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onExecute?: (rateLimiter: AsyncRateLimiter<TFn, TArgs>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn, TArgs>) => void\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n}\n\nconst defaultOptions: Required<\n Omit<AsyncRateLimiterOptions<any, any>, 'limit' | 'window'>\n> = {\n enabled: true,\n onReject: () => {},\n onError: () => {},\n onExecute: () => {},\n}\n\n/**\n * A class that creates an async rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n private _executionCount = 0\n private _executionTimes: Array<number> = []\n private _options: AsyncRateLimiterOptions<TFn, TArgs>\n private _rejectionCount = 0\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn, TArgs>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<AsyncRateLimiterOptions<TFn, TArgs>>,\n ): AsyncRateLimiterOptions<TFn, TArgs> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n return this._options\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<AsyncRateLimiterOptions<TFn, TArgs>> {\n return this._options as Required<AsyncRateLimiterOptions<TFn, TArgs>>\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n * If execution is allowed, waits for any previous execution to complete before proceeding.\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will execute\n * await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will be rejected\n * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected\n * ```\n */\n async maybeExecute(...args: TArgs): Promise<boolean> {\n this.cleanupOldExecutions()\n\n if (this._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return true\n }\n\n this.rejectFunction()\n return false\n }\n\n private async executeFunction(...args: TArgs): Promise<void> {\n if (!this._options.enabled) return\n const now = Date.now()\n this._executionCount++\n this._executionTimes.push(now)\n\n try {\n await this.fn(...args)\n } catch (error) {\n if (this._options.onError) {\n try {\n this._options.onError(error)\n } catch (error) {\n console.error('Error in onError handler', error)\n }\n }\n throw error\n } finally {\n this._options.onExecute?.(this)\n }\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this._options.window\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\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 the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this._options.limit - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow(): number {\n return this.getRemainingInWindow() * this._options.window\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._executionCount = 0\n this._rejectionCount = 0\n }\n}\n\n/**\n * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * await rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function asyncRateLimit<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n>(\n fn: TFn,\n initialOptions: Omit<AsyncRateLimiterOptions<TFn, TArgs>, 'enabled'>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":["error"],"mappings":"AAoCA,MAAM,iBAEF;AAAA,EACF,SAAS;AAAA,EACT,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAA;AACnB;AA2BO,MAAM,iBAGX;AAAA,EAMA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAiC,CAAC;AAE1C,SAAQ,kBAAkB;AAMxB,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YACqC;AACrC,SAAK,WAAW;AAAA,MACd,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAA4D;AAC1D,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmBd,MAAM,gBAAgB,MAA+B;AACnD,SAAK,qBAAqB;AAE1B,QAAI,KAAK,gBAAgB,SAAS,KAAK,SAAS,OAAO;AAC/C,YAAA,KAAK,gBAAgB,GAAG,IAAI;AAC3B,aAAA;AAAA,IAAA;AAGT,SAAK,eAAe;AACb,WAAA;AAAA,EAAA;AAAA,EAGT,MAAc,mBAAmB,MAA4B;AAtG/D;AAuGQ,QAAA,CAAC,KAAK,SAAS,QAAS;AACtB,UAAA,MAAM,KAAK,IAAI;AAChB,SAAA;AACA,SAAA,gBAAgB,KAAK,GAAG;AAEzB,QAAA;AACI,YAAA,KAAK,GAAG,GAAG,IAAI;AAAA,aACd,OAAO;AACV,UAAA,KAAK,SAAS,SAAS;AACrB,YAAA;AACG,eAAA,SAAS,QAAQ,KAAK;AAAA,iBACpBA,QAAO;AACN,kBAAA,MAAM,4BAA4BA,MAAK;AAAA,QAAA;AAAA,MACjD;AAEI,YAAA;AAAA,IAAA,UACN;AACK,uBAAA,UAAS,cAAT,4BAAqB;AAAA,IAAI;AAAA,EAChC;AAAA,EAGM,iBAAuB;AACxB,SAAA;AACD,QAAA,KAAK,SAAS,UAAU;AACrB,WAAA,SAAS,SAAS,IAAI;AAAA,IAAA;AAAA,EAC7B;AAAA,EAGM,uBAA6B;AAC7B,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,cAAc,MAAM,KAAK,SAAS;AACnC,SAAA,kBAAkB,KAAK,gBAAgB;AAAA,MAC1C,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,SAAK,qBAAqB;AACnB,WAAA,KAAK,IAAI,GAAG,KAAK,SAAS,QAAQ,KAAK,gBAAgB,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMtE,uBAA+B;AAC7B,WAAO,KAAK,qBAAA,IAAyB,KAAK,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMrD,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,kBAAkB;AACvB,SAAK,kBAAkB;AAAA,EAAA;AAE3B;AAgCgB,SAAA,eAId,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;"}
|
|
@@ -1,21 +1,26 @@
|
|
|
1
|
+
import { AnyAsyncFunction } from './types.js';
|
|
1
2
|
/**
|
|
2
3
|
* Options for configuring an async throttled function
|
|
3
4
|
*/
|
|
4
|
-
export interface AsyncThrottlerOptions {
|
|
5
|
+
export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>> {
|
|
5
6
|
/**
|
|
6
7
|
* Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
7
8
|
* Defaults to true.
|
|
8
9
|
*/
|
|
9
10
|
enabled?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Optional error handler for when the throttled function throws
|
|
13
|
+
*/
|
|
14
|
+
onError?: (error: unknown) => void;
|
|
15
|
+
/**
|
|
16
|
+
* Optional function to call when the throttled function is executed
|
|
17
|
+
*/
|
|
18
|
+
onExecute?: (throttler: AsyncThrottler<TFn, TArgs>) => void;
|
|
10
19
|
/**
|
|
11
20
|
* Time window in milliseconds during which the function can only be executed once
|
|
12
21
|
* Defaults to 0ms
|
|
13
22
|
*/
|
|
14
23
|
wait: number;
|
|
15
|
-
/**
|
|
16
|
-
* Optional error handler for when the throttled function throws
|
|
17
|
-
*/
|
|
18
|
-
onError?: (error: unknown) => void;
|
|
19
24
|
}
|
|
20
25
|
/**
|
|
21
26
|
* A class that creates an async throttled function.
|
|
@@ -39,40 +44,53 @@ export interface AsyncThrottlerOptions {
|
|
|
39
44
|
* });
|
|
40
45
|
* ```
|
|
41
46
|
*/
|
|
42
|
-
export declare class AsyncThrottler<TFn extends
|
|
47
|
+
export declare class AsyncThrottler<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>> {
|
|
43
48
|
private fn;
|
|
44
|
-
private
|
|
45
|
-
private
|
|
46
|
-
private
|
|
47
|
-
private
|
|
48
|
-
private
|
|
49
|
-
private
|
|
50
|
-
private
|
|
51
|
-
|
|
49
|
+
private _options;
|
|
50
|
+
private _abortController;
|
|
51
|
+
private _executionCount;
|
|
52
|
+
private _isExecuting;
|
|
53
|
+
private _isPending;
|
|
54
|
+
private _lastArgs;
|
|
55
|
+
private _lastExecutionTime;
|
|
56
|
+
private _nextExecutionTime;
|
|
57
|
+
constructor(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn, TArgs>);
|
|
52
58
|
/**
|
|
53
59
|
* Updates the throttler options
|
|
54
60
|
* Returns the new options state
|
|
55
61
|
*/
|
|
56
|
-
setOptions(newOptions: Partial<AsyncThrottlerOptions
|
|
62
|
+
setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn, TArgs>>): Required<AsyncThrottlerOptions<TFn, TArgs>>;
|
|
57
63
|
/**
|
|
58
|
-
* Returns the
|
|
64
|
+
* Returns the current options
|
|
59
65
|
*/
|
|
60
|
-
|
|
66
|
+
getOptions(): Required<AsyncThrottlerOptions<TFn, TArgs>>;
|
|
61
67
|
/**
|
|
62
|
-
*
|
|
68
|
+
* Attempts to execute the throttled function
|
|
69
|
+
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
63
70
|
*/
|
|
64
|
-
|
|
71
|
+
maybeExecute(...args: TArgs): Promise<void>;
|
|
72
|
+
private delay;
|
|
73
|
+
private executeFunction;
|
|
65
74
|
/**
|
|
66
75
|
* Cancels any pending execution
|
|
67
76
|
*/
|
|
68
77
|
cancel(): void;
|
|
69
78
|
/**
|
|
70
|
-
*
|
|
71
|
-
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
79
|
+
* Returns the number of times the function has been executed
|
|
72
80
|
*/
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
81
|
+
getExecutionCount(): number;
|
|
82
|
+
/**
|
|
83
|
+
* Returns the last execution time
|
|
84
|
+
*/
|
|
85
|
+
getLastExecutionTime(): number;
|
|
86
|
+
/**
|
|
87
|
+
* Returns the next execution time
|
|
88
|
+
*/
|
|
89
|
+
getNextExecutionTime(): number;
|
|
90
|
+
/**
|
|
91
|
+
* Returns the current pending state
|
|
92
|
+
*/
|
|
93
|
+
getIsPending(): boolean;
|
|
76
94
|
}
|
|
77
95
|
/**
|
|
78
96
|
* Creates an async throttled function that limits how often the function can execute.
|
|
@@ -90,4 +108,4 @@ export declare class AsyncThrottler<TFn extends (...args: Array<any>) => Promise
|
|
|
90
108
|
* await throttled(); // Waits 1 second before executing
|
|
91
109
|
* ```
|
|
92
110
|
*/
|
|
93
|
-
export declare function asyncThrottle<TFn extends
|
|
111
|
+
export declare function asyncThrottle<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions<TFn, TArgs>, 'enabled'>): (...args: TArgs) => Promise<void>;
|
|
@@ -2,17 +2,20 @@ const defaultOptions = {
|
|
|
2
2
|
enabled: true,
|
|
3
3
|
onError: () => {
|
|
4
4
|
},
|
|
5
|
+
onExecute: () => {
|
|
6
|
+
},
|
|
5
7
|
wait: 0
|
|
6
8
|
};
|
|
7
9
|
class AsyncThrottler {
|
|
8
10
|
constructor(fn, initialOptions) {
|
|
9
11
|
this.fn = fn;
|
|
10
|
-
this.
|
|
11
|
-
this.
|
|
12
|
-
this.
|
|
13
|
-
this.
|
|
14
|
-
this.
|
|
15
|
-
this.
|
|
12
|
+
this._abortController = null;
|
|
13
|
+
this._executionCount = 0;
|
|
14
|
+
this._isExecuting = false;
|
|
15
|
+
this._isPending = false;
|
|
16
|
+
this._lastExecutionTime = 0;
|
|
17
|
+
this._nextExecutionTime = 0;
|
|
18
|
+
this._options = {
|
|
16
19
|
...defaultOptions,
|
|
17
20
|
...initialOptions
|
|
18
21
|
};
|
|
@@ -22,67 +25,51 @@ class AsyncThrottler {
|
|
|
22
25
|
* Returns the new options state
|
|
23
26
|
*/
|
|
24
27
|
setOptions(newOptions) {
|
|
25
|
-
this.
|
|
26
|
-
...this.
|
|
28
|
+
this._options = {
|
|
29
|
+
...this._options,
|
|
27
30
|
...newOptions
|
|
28
31
|
};
|
|
29
|
-
return this.
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Returns the number of times the function has been executed
|
|
33
|
-
*/
|
|
34
|
-
getExecutionCount() {
|
|
35
|
-
return this.executionCount;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Returns the next execution time
|
|
39
|
-
*/
|
|
40
|
-
getNextExecutionTime() {
|
|
41
|
-
return this.nextExecutionTime;
|
|
32
|
+
return this._options;
|
|
42
33
|
}
|
|
43
34
|
/**
|
|
44
|
-
*
|
|
35
|
+
* Returns the current options
|
|
45
36
|
*/
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
this.abortController.abort();
|
|
49
|
-
this.abortController = null;
|
|
50
|
-
}
|
|
51
|
-
this.isScheduled = false;
|
|
52
|
-
this.lastArgs = void 0;
|
|
37
|
+
getOptions() {
|
|
38
|
+
return this._options;
|
|
53
39
|
}
|
|
54
40
|
/**
|
|
55
41
|
* Attempts to execute the throttled function
|
|
56
42
|
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
57
43
|
*/
|
|
58
44
|
async maybeExecute(...args) {
|
|
59
|
-
this.
|
|
60
|
-
if (this.
|
|
61
|
-
this.
|
|
62
|
-
this.
|
|
63
|
-
const signal = this.
|
|
45
|
+
this._lastArgs = args;
|
|
46
|
+
if (this._isPending) return;
|
|
47
|
+
this._isPending = true;
|
|
48
|
+
this._abortController = new AbortController();
|
|
49
|
+
const signal = this._abortController.signal;
|
|
64
50
|
try {
|
|
65
|
-
while (this.
|
|
66
|
-
await this.delay(this.
|
|
51
|
+
while (this._isExecuting) {
|
|
52
|
+
await this.delay(this._options.wait, signal);
|
|
67
53
|
}
|
|
68
|
-
while (Date.now() < this.
|
|
69
|
-
await this.delay(this.
|
|
54
|
+
while (Date.now() < this._nextExecutionTime) {
|
|
55
|
+
await this.delay(this._nextExecutionTime - Date.now(), signal);
|
|
70
56
|
}
|
|
71
|
-
this.
|
|
72
|
-
this.
|
|
73
|
-
await this.executeFunction(...this.
|
|
57
|
+
this._isPending = false;
|
|
58
|
+
this._isExecuting = true;
|
|
59
|
+
await this.executeFunction(...this._lastArgs);
|
|
74
60
|
} catch (error) {
|
|
75
61
|
if (error instanceof Error && error.name === "AbortError") {
|
|
76
62
|
return;
|
|
77
63
|
}
|
|
78
64
|
try {
|
|
79
|
-
this.
|
|
65
|
+
this._options.onError(error);
|
|
80
66
|
} catch {
|
|
81
67
|
}
|
|
82
68
|
} finally {
|
|
83
|
-
this.
|
|
84
|
-
this.
|
|
85
|
-
this.
|
|
69
|
+
this._lastExecutionTime = Date.now();
|
|
70
|
+
this._nextExecutionTime = this._lastExecutionTime + this._options.wait;
|
|
71
|
+
this._isExecuting = false;
|
|
72
|
+
this._abortController = null;
|
|
86
73
|
}
|
|
87
74
|
}
|
|
88
75
|
delay(ms, signal) {
|
|
@@ -99,9 +86,45 @@ class AsyncThrottler {
|
|
|
99
86
|
});
|
|
100
87
|
}
|
|
101
88
|
async executeFunction(...args) {
|
|
102
|
-
if (!this.
|
|
103
|
-
this.
|
|
89
|
+
if (!this._options.enabled) return;
|
|
90
|
+
this._executionCount++;
|
|
104
91
|
await this.fn(...args);
|
|
92
|
+
this._options.onExecute(this);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Cancels any pending execution
|
|
96
|
+
*/
|
|
97
|
+
cancel() {
|
|
98
|
+
if (this._abortController) {
|
|
99
|
+
this._abortController.abort();
|
|
100
|
+
this._abortController = null;
|
|
101
|
+
}
|
|
102
|
+
this._isPending = false;
|
|
103
|
+
this._lastArgs = void 0;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Returns the number of times the function has been executed
|
|
107
|
+
*/
|
|
108
|
+
getExecutionCount() {
|
|
109
|
+
return this._executionCount;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Returns the last execution time
|
|
113
|
+
*/
|
|
114
|
+
getLastExecutionTime() {
|
|
115
|
+
return this._lastExecutionTime;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Returns the next execution time
|
|
119
|
+
*/
|
|
120
|
+
getNextExecutionTime() {
|
|
121
|
+
return this._nextExecutionTime;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Returns the current pending state
|
|
125
|
+
*/
|
|
126
|
+
getIsPending() {
|
|
127
|
+
return this._isPending;
|
|
105
128
|
}
|
|
106
129
|
}
|
|
107
130
|
function asyncThrottle(fn, initialOptions) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-throttler.js","sources":["../../src/async-throttler.ts"],"sourcesContent":["/**\n * Options for configuring an async throttled function\n */\nexport interface AsyncThrottlerOptions {\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 *
|
|
1
|
+
{"version":3,"file":"async-throttler.js","sources":["../../src/async-throttler.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async throttled function\n */\nexport interface AsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\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 * Optional error handler for when the throttled function throws\n */\n onError?: (error: unknown) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onExecute?: (throttler: AsyncThrottler<TFn, TArgs>) => void\n /**\n * Time window in milliseconds during which the function can only be executed once\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<AsyncThrottlerOptions<any, any>> = {\n enabled: true,\n onError: () => {},\n onExecute: () => {},\n wait: 0,\n}\n\n/**\n * A class that creates an async throttled function.\n *\n * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.\n * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a\n * regular interval regardless of how often it's called.\n *\n * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to\n * ensure a maximum execution frequency.\n *\n * @example\n * ```ts\n * const throttler = new AsyncThrottler(async (value: string) => {\n * await saveToAPI(value);\n * }, { wait: 1000 });\n *\n * // Will only execute once per second no matter how often called\n * inputElement.addEventListener('input', () => {\n * throttler.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class AsyncThrottler<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n private _options: Required<AsyncThrottlerOptions<TFn, TArgs>>\n private _abortController: AbortController | null = null\n private _executionCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: TArgs | undefined\n private _lastExecutionTime = 0\n private _nextExecutionTime = 0\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn, TArgs>,\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(\n newOptions: Partial<AsyncThrottlerOptions<TFn, TArgs>>,\n ): Required<AsyncThrottlerOptions<TFn, TArgs>> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n return this._options\n }\n\n /**\n * Returns the current options\n */\n getOptions(): Required<AsyncThrottlerOptions<TFn, TArgs>> {\n return this._options\n }\n\n /**\n * Attempts to execute the throttled function\n * If a call is already in progress, it may be blocked or queued depending on the `wait` option\n */\n async maybeExecute(...args: TArgs): Promise<void> {\n this._lastArgs = args\n if (this._isPending) return\n this._isPending = true\n\n this._abortController = new AbortController()\n const signal = this._abortController.signal\n\n try {\n while (this._isExecuting) {\n await this.delay(this._options.wait, signal)\n }\n\n while (Date.now() < this._nextExecutionTime) {\n await this.delay(this._nextExecutionTime - Date.now(), signal)\n }\n\n this._isPending = false\n this._isExecuting = true\n\n await this.executeFunction(...this._lastArgs)\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n return // Silent return on cancellation\n }\n try {\n this._options.onError(error)\n } catch {\n // Ignore errors from error handler\n }\n } finally {\n this._lastExecutionTime = Date.now()\n this._nextExecutionTime = this._lastExecutionTime + this._options.wait\n this._isExecuting = false\n this._abortController = null\n }\n }\n\n private delay(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(resolve, ms)\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timeout)\n reject(new Error('AbortError'))\n },\n { once: true },\n )\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._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._isPending = false\n this._lastArgs = undefined\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 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._nextExecutionTime\n }\n\n /**\n * Returns the current pending state\n */\n getIsPending(): boolean {\n return this._isPending\n }\n}\n\n/**\n * Creates an async throttled function that limits how often the function can execute.\n * The throttled function will execute at most once per wait period, even if called multiple times.\n * If called while executing, it will wait until execution completes before scheduling the next call.\n *\n * @example\n * ```ts\n * const throttled = asyncThrottle(async () => {\n * await someAsyncOperation();\n * }, { wait: 1000 });\n *\n * // This will execute at most once per second\n * await throttled();\n * await throttled(); // Waits 1 second before executing\n * ```\n */\nexport function asyncThrottle<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions<TFn, TArgs>, 'enabled'>) {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n return asyncThrottler.maybeExecute.bind(asyncThrottler)\n}\n"],"names":[],"mappings":"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"}
|
package/dist/esm/debouncer.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { AnyFunction } from './types.js';
|
|
1
2
|
/**
|
|
2
3
|
* Options for configuring a debounced function
|
|
3
4
|
*/
|
|
4
|
-
export interface DebouncerOptions {
|
|
5
|
+
export interface DebouncerOptions<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
|
|
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,10 @@ export interface DebouncerOptions {
|
|
|
12
13
|
* Defaults to false.
|
|
13
14
|
*/
|
|
14
15
|
leading?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Callback function that is called after the function is executed
|
|
18
|
+
*/
|
|
19
|
+
onExecute?: (debouncer: Debouncer<TFn, TArgs>) => void;
|
|
15
20
|
/**
|
|
16
21
|
* Whether to execute on the trailing edge of the timeout.
|
|
17
22
|
* Defaults to true.
|
|
@@ -46,22 +51,23 @@ export interface DebouncerOptions {
|
|
|
46
51
|
* });
|
|
47
52
|
* ```
|
|
48
53
|
*/
|
|
49
|
-
export declare class Debouncer<TFn extends
|
|
54
|
+
export declare class Debouncer<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
|
|
50
55
|
private fn;
|
|
51
|
-
private
|
|
52
|
-
private
|
|
53
|
-
private
|
|
54
|
-
private
|
|
55
|
-
|
|
56
|
+
private _canLeadingExecute;
|
|
57
|
+
private _isPending;
|
|
58
|
+
private _executionCount;
|
|
59
|
+
private _options;
|
|
60
|
+
private _timeoutId;
|
|
61
|
+
constructor(fn: TFn, initialOptions: DebouncerOptions<TFn, TArgs>);
|
|
56
62
|
/**
|
|
57
63
|
* Updates the debouncer options
|
|
58
64
|
* Returns the new options state
|
|
59
65
|
*/
|
|
60
|
-
setOptions(newOptions: Partial<DebouncerOptions
|
|
66
|
+
setOptions(newOptions: Partial<DebouncerOptions<TFn, TArgs>>): Required<DebouncerOptions<TFn, TArgs>>;
|
|
61
67
|
/**
|
|
62
|
-
* Returns the
|
|
68
|
+
* Returns the current debouncer options
|
|
63
69
|
*/
|
|
64
|
-
|
|
70
|
+
getOptions(): Required<DebouncerOptions<TFn, TArgs>>;
|
|
65
71
|
/**
|
|
66
72
|
* Attempts to execute the debounced function
|
|
67
73
|
* If a call is already in progress, it will be queued
|
|
@@ -72,6 +78,14 @@ export declare class Debouncer<TFn extends (...args: Array<any>) => any, TArgs e
|
|
|
72
78
|
* Cancels any pending execution
|
|
73
79
|
*/
|
|
74
80
|
cancel(): void;
|
|
81
|
+
/**
|
|
82
|
+
* Returns the number of times the function has been executed
|
|
83
|
+
*/
|
|
84
|
+
getExecutionCount(): number;
|
|
85
|
+
/**
|
|
86
|
+
* Returns `true` if debouncing
|
|
87
|
+
*/
|
|
88
|
+
getIsPending(): boolean;
|
|
75
89
|
}
|
|
76
90
|
/**
|
|
77
91
|
* Creates a debounced function that delays invoking the provided function until after a specified wait time.
|
|
@@ -93,4 +107,4 @@ export declare class Debouncer<TFn extends (...args: Array<any>) => any, TArgs e
|
|
|
93
107
|
* inputElement.addEventListener('input', debounced);
|
|
94
108
|
* ```
|
|
95
109
|
*/
|
|
96
|
-
export declare function debounce<TFn extends
|
|
110
|
+
export declare function debounce<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<DebouncerOptions<TFn, Parameters<TFn>>, 'enabled'>): (...args: Parameters<TFn>) => void;
|