@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
|
@@ -4,17 +4,20 @@ const defaultOptions = {
|
|
|
4
4
|
enabled: true,
|
|
5
5
|
onError: () => {
|
|
6
6
|
},
|
|
7
|
+
onExecute: () => {
|
|
8
|
+
},
|
|
7
9
|
wait: 0
|
|
8
10
|
};
|
|
9
11
|
class AsyncThrottler {
|
|
10
12
|
constructor(fn, initialOptions) {
|
|
11
13
|
this.fn = fn;
|
|
12
|
-
this.
|
|
13
|
-
this.
|
|
14
|
-
this.
|
|
15
|
-
this.
|
|
16
|
-
this.
|
|
17
|
-
this.
|
|
14
|
+
this._abortController = null;
|
|
15
|
+
this._executionCount = 0;
|
|
16
|
+
this._isExecuting = false;
|
|
17
|
+
this._isPending = false;
|
|
18
|
+
this._lastExecutionTime = 0;
|
|
19
|
+
this._nextExecutionTime = 0;
|
|
20
|
+
this._options = {
|
|
18
21
|
...defaultOptions,
|
|
19
22
|
...initialOptions
|
|
20
23
|
};
|
|
@@ -24,67 +27,51 @@ class AsyncThrottler {
|
|
|
24
27
|
* Returns the new options state
|
|
25
28
|
*/
|
|
26
29
|
setOptions(newOptions) {
|
|
27
|
-
this.
|
|
28
|
-
...this.
|
|
30
|
+
this._options = {
|
|
31
|
+
...this._options,
|
|
29
32
|
...newOptions
|
|
30
33
|
};
|
|
31
|
-
return this.
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Returns the number of times the function has been executed
|
|
35
|
-
*/
|
|
36
|
-
getExecutionCount() {
|
|
37
|
-
return this.executionCount;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Returns the next execution time
|
|
41
|
-
*/
|
|
42
|
-
getNextExecutionTime() {
|
|
43
|
-
return this.nextExecutionTime;
|
|
34
|
+
return this._options;
|
|
44
35
|
}
|
|
45
36
|
/**
|
|
46
|
-
*
|
|
37
|
+
* Returns the current options
|
|
47
38
|
*/
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
this.abortController.abort();
|
|
51
|
-
this.abortController = null;
|
|
52
|
-
}
|
|
53
|
-
this.isScheduled = false;
|
|
54
|
-
this.lastArgs = void 0;
|
|
39
|
+
getOptions() {
|
|
40
|
+
return this._options;
|
|
55
41
|
}
|
|
56
42
|
/**
|
|
57
43
|
* Attempts to execute the throttled function
|
|
58
44
|
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
59
45
|
*/
|
|
60
46
|
async maybeExecute(...args) {
|
|
61
|
-
this.
|
|
62
|
-
if (this.
|
|
63
|
-
this.
|
|
64
|
-
this.
|
|
65
|
-
const signal = this.
|
|
47
|
+
this._lastArgs = args;
|
|
48
|
+
if (this._isPending) return;
|
|
49
|
+
this._isPending = true;
|
|
50
|
+
this._abortController = new AbortController();
|
|
51
|
+
const signal = this._abortController.signal;
|
|
66
52
|
try {
|
|
67
|
-
while (this.
|
|
68
|
-
await this.delay(this.
|
|
53
|
+
while (this._isExecuting) {
|
|
54
|
+
await this.delay(this._options.wait, signal);
|
|
69
55
|
}
|
|
70
|
-
while (Date.now() < this.
|
|
71
|
-
await this.delay(this.
|
|
56
|
+
while (Date.now() < this._nextExecutionTime) {
|
|
57
|
+
await this.delay(this._nextExecutionTime - Date.now(), signal);
|
|
72
58
|
}
|
|
73
|
-
this.
|
|
74
|
-
this.
|
|
75
|
-
await this.executeFunction(...this.
|
|
59
|
+
this._isPending = false;
|
|
60
|
+
this._isExecuting = true;
|
|
61
|
+
await this.executeFunction(...this._lastArgs);
|
|
76
62
|
} catch (error) {
|
|
77
63
|
if (error instanceof Error && error.name === "AbortError") {
|
|
78
64
|
return;
|
|
79
65
|
}
|
|
80
66
|
try {
|
|
81
|
-
this.
|
|
67
|
+
this._options.onError(error);
|
|
82
68
|
} catch {
|
|
83
69
|
}
|
|
84
70
|
} finally {
|
|
85
|
-
this.
|
|
86
|
-
this.
|
|
87
|
-
this.
|
|
71
|
+
this._lastExecutionTime = Date.now();
|
|
72
|
+
this._nextExecutionTime = this._lastExecutionTime + this._options.wait;
|
|
73
|
+
this._isExecuting = false;
|
|
74
|
+
this._abortController = null;
|
|
88
75
|
}
|
|
89
76
|
}
|
|
90
77
|
delay(ms, signal) {
|
|
@@ -101,9 +88,45 @@ class AsyncThrottler {
|
|
|
101
88
|
});
|
|
102
89
|
}
|
|
103
90
|
async executeFunction(...args) {
|
|
104
|
-
if (!this.
|
|
105
|
-
this.
|
|
91
|
+
if (!this._options.enabled) return;
|
|
92
|
+
this._executionCount++;
|
|
106
93
|
await this.fn(...args);
|
|
94
|
+
this._options.onExecute(this);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Cancels any pending execution
|
|
98
|
+
*/
|
|
99
|
+
cancel() {
|
|
100
|
+
if (this._abortController) {
|
|
101
|
+
this._abortController.abort();
|
|
102
|
+
this._abortController = null;
|
|
103
|
+
}
|
|
104
|
+
this._isPending = false;
|
|
105
|
+
this._lastArgs = void 0;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Returns the number of times the function has been executed
|
|
109
|
+
*/
|
|
110
|
+
getExecutionCount() {
|
|
111
|
+
return this._executionCount;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Returns the last execution time
|
|
115
|
+
*/
|
|
116
|
+
getLastExecutionTime() {
|
|
117
|
+
return this._lastExecutionTime;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Returns the next execution time
|
|
121
|
+
*/
|
|
122
|
+
getNextExecutionTime() {
|
|
123
|
+
return this._nextExecutionTime;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Returns the current pending state
|
|
127
|
+
*/
|
|
128
|
+
getIsPending() {
|
|
129
|
+
return this._isPending;
|
|
107
130
|
}
|
|
108
131
|
}
|
|
109
132
|
function asyncThrottle(fn, initialOptions) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-throttler.cjs","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.cjs","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":";;AA6BA,MAAM,iBAA4D;AAAA,EAChE,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,MAAM;AACR;AAwBO,MAAM,eAGX;AAAA,EAUA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,mBAA2C;AACnD,SAAQ,kBAAkB;AAC1B,SAAQ,eAAe;AACvB,SAAQ,aAAa;AAErB,SAAQ,qBAAqB;AAC7B,SAAQ,qBAAqB;AAM3B,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YAC6C;AAC7C,SAAK,WAAW;AAAA,MACd,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAA0D;AACxD,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,MAAM,gBAAgB,MAA4B;AAChD,SAAK,YAAY;AACjB,QAAI,KAAK,WAAY;AACrB,SAAK,aAAa;AAEb,SAAA,mBAAmB,IAAI,gBAAgB;AACtC,UAAA,SAAS,KAAK,iBAAiB;AAEjC,QAAA;AACF,aAAO,KAAK,cAAc;AACxB,cAAM,KAAK,MAAM,KAAK,SAAS,MAAM,MAA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EAMd,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAkBgB,SAAA,cAGd,IAAS,gBAAoE;AAC7E,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}
|
|
@@ -1,21 +1,26 @@
|
|
|
1
|
+
import { AnyAsyncFunction } from './types.cjs';
|
|
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>;
|
package/dist/cjs/debouncer.cjs
CHANGED
|
@@ -4,14 +4,17 @@ const defaultOptions = {
|
|
|
4
4
|
enabled: true,
|
|
5
5
|
leading: false,
|
|
6
6
|
trailing: true,
|
|
7
|
-
wait: 0
|
|
7
|
+
wait: 0,
|
|
8
|
+
onExecute: () => {
|
|
9
|
+
}
|
|
8
10
|
};
|
|
9
11
|
class Debouncer {
|
|
10
12
|
constructor(fn, initialOptions) {
|
|
11
13
|
this.fn = fn;
|
|
12
|
-
this.
|
|
13
|
-
this.
|
|
14
|
-
this.
|
|
14
|
+
this._canLeadingExecute = true;
|
|
15
|
+
this._isPending = false;
|
|
16
|
+
this._executionCount = 0;
|
|
17
|
+
this._options = {
|
|
15
18
|
...defaultOptions,
|
|
16
19
|
...initialOptions
|
|
17
20
|
};
|
|
@@ -21,49 +24,70 @@ class Debouncer {
|
|
|
21
24
|
* Returns the new options state
|
|
22
25
|
*/
|
|
23
26
|
setOptions(newOptions) {
|
|
24
|
-
this.
|
|
25
|
-
...this.
|
|
27
|
+
this._options = {
|
|
28
|
+
...this._options,
|
|
26
29
|
...newOptions
|
|
27
30
|
};
|
|
28
|
-
|
|
31
|
+
if (!this._options.enabled) {
|
|
32
|
+
this._isPending = false;
|
|
33
|
+
}
|
|
34
|
+
return this._options;
|
|
29
35
|
}
|
|
30
36
|
/**
|
|
31
|
-
* Returns the
|
|
37
|
+
* Returns the current debouncer options
|
|
32
38
|
*/
|
|
33
|
-
|
|
34
|
-
return this.
|
|
39
|
+
getOptions() {
|
|
40
|
+
return this._options;
|
|
35
41
|
}
|
|
36
42
|
/**
|
|
37
43
|
* Attempts to execute the debounced function
|
|
38
44
|
* If a call is already in progress, it will be queued
|
|
39
45
|
*/
|
|
40
46
|
maybeExecute(...args) {
|
|
41
|
-
if (this.
|
|
47
|
+
if (this._options.leading && this._canLeadingExecute) {
|
|
42
48
|
this.executeFunction(...args);
|
|
43
|
-
this.
|
|
49
|
+
this._canLeadingExecute = false;
|
|
44
50
|
}
|
|
45
|
-
if (this.
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
51
|
+
if (this._options.leading || this._options.trailing) {
|
|
52
|
+
this._isPending = true;
|
|
53
|
+
}
|
|
54
|
+
if (this._timeoutId) clearTimeout(this._timeoutId);
|
|
55
|
+
this._timeoutId = setTimeout(() => {
|
|
56
|
+
this._canLeadingExecute = true;
|
|
57
|
+
this._isPending = false;
|
|
58
|
+
if (this._options.trailing) {
|
|
49
59
|
this.executeFunction(...args);
|
|
50
60
|
}
|
|
51
|
-
}, this.
|
|
61
|
+
}, this._options.wait);
|
|
52
62
|
}
|
|
53
63
|
executeFunction(...args) {
|
|
54
|
-
if (!this.
|
|
55
|
-
this.executionCount++;
|
|
64
|
+
if (!this._options.enabled) return;
|
|
56
65
|
this.fn(...args);
|
|
66
|
+
this._executionCount++;
|
|
67
|
+
this._options.onExecute(this);
|
|
57
68
|
}
|
|
58
69
|
/**
|
|
59
70
|
* Cancels any pending execution
|
|
60
71
|
*/
|
|
61
72
|
cancel() {
|
|
62
|
-
if (this.
|
|
63
|
-
clearTimeout(this.
|
|
64
|
-
this.
|
|
73
|
+
if (this._timeoutId) {
|
|
74
|
+
clearTimeout(this._timeoutId);
|
|
75
|
+
this._canLeadingExecute = true;
|
|
76
|
+
this._isPending = false;
|
|
65
77
|
}
|
|
66
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* Returns the number of times the function has been executed
|
|
81
|
+
*/
|
|
82
|
+
getExecutionCount() {
|
|
83
|
+
return this._executionCount;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Returns `true` if debouncing
|
|
87
|
+
*/
|
|
88
|
+
getIsPending() {
|
|
89
|
+
return this._options.enabled && this._isPending;
|
|
90
|
+
}
|
|
67
91
|
}
|
|
68
92
|
function debounce(fn, initialOptions) {
|
|
69
93
|
const debouncer = new Debouncer(fn, initialOptions);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debouncer.cjs","sources":["../../src/debouncer.ts"],"sourcesContent":["/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions {\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 before executing the function\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<DebouncerOptions
|
|
1
|
+
{"version":3,"file":"debouncer.cjs","sources":["../../src/debouncer.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<\n TFn extends AnyFunction,\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 * Callback function that is called after the function is executed\n */\n onExecute?: (debouncer: Debouncer<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 before executing the function\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<DebouncerOptions<any, any>> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n onExecute: () => {},\n}\n\n/**\n * A class that creates a debounced function.\n *\n * Debouncing ensures that a function is only executed after a certain amount of time has passed\n * since its last invocation. This is useful for handling frequent events like window resizing,\n * scroll events, or input changes where you want to limit the rate of execution.\n *\n * The debounced function can be configured to execute either at the start of the delay period\n * (leading edge) or at the end (trailing edge, default). Each new call during the wait period\n * will reset the timer.\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\n *\n * // Will only save after 500ms of no new input\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class Debouncer<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {\n private _canLeadingExecute = true\n private _isPending = false\n private _executionCount = 0\n private _options: Required<DebouncerOptions<TFn, TArgs>>\n private _timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: DebouncerOptions<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<DebouncerOptions<TFn, TArgs>>,\n ): Required<DebouncerOptions<TFn, TArgs>> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n\n return this._options\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<DebouncerOptions<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 maybeExecute(...args: TArgs): void {\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this.executeFunction(...args)\n this._canLeadingExecute = false\n }\n\n // Start pending state\n if (this._options.leading || this._options.trailing) {\n this._isPending = true\n }\n\n // Clear any existing timeout\n if (this._timeoutId) clearTimeout(this._timeoutId)\n\n // Set new timeout that will reset canLeadingExecute\n this._timeoutId = setTimeout(() => {\n this._canLeadingExecute = true\n this._isPending = false\n // Execute trailing only if enabled\n if (this._options.trailing) {\n this.executeFunction(...args)\n }\n }, this._options.wait)\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this._options.enabled) return\n this.fn(...args) // EXECUTE!\n this._executionCount++\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._canLeadingExecute = true\n this._isPending = false\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 `true` if debouncing\n */\n getIsPending(): boolean {\n return this._options.enabled && this._isPending\n }\n}\n\n/**\n * Creates a debounced function that delays invoking the provided function until after a specified wait time.\n * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.\n *\n * This the the simple function wrapper implementation pulled from the Debouncer class. If you need\n * more control over the debouncing behavior, use the Debouncer class directly.\n *\n * If leading option is true, the function will execute immediately on the first call, then wait the delay\n * before allowing another execution.\n *\n * @example\n * ```ts\n * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: Omit<DebouncerOptions<TFn, Parameters<TFn>>, 'enabled'>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AC,KAAK,SAAS,QAAS;AACvB,SAAA,GAAG,GAAG,IAAI;AACV,SAAA;AACA,SAAA,SAAS,UAAU,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM9B,SAAe;AACb,QAAI,KAAK,YAAY;AACnB,mBAAa,KAAK,UAAU;AAC5B,WAAK,qBAAqB;AAC1B,WAAK,aAAa;AAAA,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAMF,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,SAAS,WAAW,KAAK;AAAA,EAAA;AAEzC;AAsBgB,SAAA,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;;;"}
|
package/dist/cjs/debouncer.d.cts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { AnyFunction } from './types.cjs';
|
|
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;
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -9,6 +9,7 @@ const debouncer = require("./debouncer.cjs");
|
|
|
9
9
|
const queuer = require("./queuer.cjs");
|
|
10
10
|
const rateLimiter = require("./rate-limiter.cjs");
|
|
11
11
|
const throttler = require("./throttler.cjs");
|
|
12
|
+
const utils = require("./utils.cjs");
|
|
12
13
|
exports.AsyncDebouncer = asyncDebouncer.AsyncDebouncer;
|
|
13
14
|
exports.asyncDebounce = asyncDebouncer.asyncDebounce;
|
|
14
15
|
exports.AsyncQueuer = asyncQueuer.AsyncQueuer;
|
|
@@ -29,4 +30,5 @@ exports.RateLimiter = rateLimiter.RateLimiter;
|
|
|
29
30
|
exports.rateLimit = rateLimiter.rateLimit;
|
|
30
31
|
exports.Throttler = throttler.Throttler;
|
|
31
32
|
exports.throttle = throttler.throttle;
|
|
33
|
+
exports.bindInstanceMethods = utils.bindInstanceMethods;
|
|
32
34
|
//# sourceMappingURL=index.cjs.map
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|