@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
|
@@ -1,18 +1,27 @@
|
|
|
1
1
|
const defaultOptions = {
|
|
2
2
|
enabled: true,
|
|
3
|
+
leading: true,
|
|
3
4
|
onError: () => {
|
|
4
5
|
},
|
|
6
|
+
onSettled: () => {
|
|
7
|
+
},
|
|
8
|
+
onSuccess: () => {
|
|
9
|
+
},
|
|
10
|
+
trailing: true,
|
|
5
11
|
wait: 0
|
|
6
12
|
};
|
|
7
13
|
class AsyncThrottler {
|
|
8
14
|
constructor(fn, initialOptions) {
|
|
9
15
|
this.fn = fn;
|
|
10
|
-
this.
|
|
11
|
-
this.
|
|
12
|
-
this.
|
|
13
|
-
this.
|
|
14
|
-
this.
|
|
15
|
-
this.
|
|
16
|
+
this._abortController = null;
|
|
17
|
+
this._errorCount = 0;
|
|
18
|
+
this._isExecuting = false;
|
|
19
|
+
this._lastExecutionTime = 0;
|
|
20
|
+
this._nextExecutionTime = 0;
|
|
21
|
+
this._settleCount = 0;
|
|
22
|
+
this._successCount = 0;
|
|
23
|
+
this._timeoutId = null;
|
|
24
|
+
this._options = {
|
|
16
25
|
...defaultOptions,
|
|
17
26
|
...initialOptions
|
|
18
27
|
};
|
|
@@ -22,86 +31,128 @@ class AsyncThrottler {
|
|
|
22
31
|
* Returns the new options state
|
|
23
32
|
*/
|
|
24
33
|
setOptions(newOptions) {
|
|
25
|
-
this.
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
return this.options;
|
|
34
|
+
this._options = { ...this._options, ...newOptions };
|
|
35
|
+
if (!this._options.enabled) {
|
|
36
|
+
this.cancel();
|
|
37
|
+
}
|
|
30
38
|
}
|
|
31
39
|
/**
|
|
32
|
-
* Returns the
|
|
40
|
+
* Returns the current options
|
|
33
41
|
*/
|
|
34
|
-
|
|
35
|
-
return this.
|
|
42
|
+
getOptions() {
|
|
43
|
+
return this._options;
|
|
36
44
|
}
|
|
37
45
|
/**
|
|
38
|
-
*
|
|
46
|
+
* Attempts to execute the throttled function
|
|
47
|
+
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
39
48
|
*/
|
|
40
|
-
|
|
41
|
-
|
|
49
|
+
async maybeExecute(...args) {
|
|
50
|
+
const now = Date.now();
|
|
51
|
+
const timeSinceLastExecution = now - this._lastExecutionTime;
|
|
52
|
+
if (this._options.leading && timeSinceLastExecution >= this._options.wait) {
|
|
53
|
+
await this.executeFunction(...args);
|
|
54
|
+
return this._lastResult;
|
|
55
|
+
} else {
|
|
56
|
+
this._lastArgs = args;
|
|
57
|
+
return new Promise((resolve) => {
|
|
58
|
+
if (this._timeoutId) {
|
|
59
|
+
clearTimeout(this._timeoutId);
|
|
60
|
+
}
|
|
61
|
+
if (this._options.trailing) {
|
|
62
|
+
const _timeSinceLastExecution = this._lastExecutionTime ? now - this._lastExecutionTime : 0;
|
|
63
|
+
const timeoutDuration = this._options.wait - _timeSinceLastExecution;
|
|
64
|
+
this._timeoutId = setTimeout(async () => {
|
|
65
|
+
if (this._lastArgs !== void 0) {
|
|
66
|
+
await this.executeFunction(...this._lastArgs);
|
|
67
|
+
}
|
|
68
|
+
resolve(this._lastResult);
|
|
69
|
+
}, timeoutDuration);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async executeFunction(...args) {
|
|
75
|
+
if (!this._options.enabled || this._isExecuting) return void 0;
|
|
76
|
+
this._abortController = new AbortController();
|
|
77
|
+
try {
|
|
78
|
+
this._isExecuting = true;
|
|
79
|
+
this._lastResult = await this.fn(...args);
|
|
80
|
+
this._successCount++;
|
|
81
|
+
this._options.onSuccess(this._lastResult, this);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
this._errorCount++;
|
|
84
|
+
this._options.onError(error, this);
|
|
85
|
+
} finally {
|
|
86
|
+
this._isExecuting = false;
|
|
87
|
+
this._settleCount++;
|
|
88
|
+
this._abortController = null;
|
|
89
|
+
this._lastExecutionTime = Date.now();
|
|
90
|
+
this._nextExecutionTime = this._lastExecutionTime + this._options.wait;
|
|
91
|
+
this._options.onSettled(this);
|
|
92
|
+
}
|
|
93
|
+
return this._lastResult;
|
|
42
94
|
}
|
|
43
95
|
/**
|
|
44
|
-
* Cancels any pending execution
|
|
96
|
+
* Cancels any pending execution or aborts any execution in progress
|
|
45
97
|
*/
|
|
46
98
|
cancel() {
|
|
47
|
-
if (this.
|
|
48
|
-
this.
|
|
49
|
-
this.
|
|
99
|
+
if (this._timeoutId) {
|
|
100
|
+
clearTimeout(this._timeoutId);
|
|
101
|
+
this._timeoutId = null;
|
|
102
|
+
}
|
|
103
|
+
if (this._abortController) {
|
|
104
|
+
this._abortController.abort();
|
|
105
|
+
this._abortController = null;
|
|
50
106
|
}
|
|
51
|
-
this.
|
|
52
|
-
this.lastArgs = void 0;
|
|
107
|
+
this._lastArgs = void 0;
|
|
53
108
|
}
|
|
54
109
|
/**
|
|
55
|
-
*
|
|
56
|
-
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
110
|
+
* Returns the last execution time
|
|
57
111
|
*/
|
|
58
|
-
|
|
59
|
-
this.
|
|
60
|
-
if (this.isScheduled) return;
|
|
61
|
-
this.isScheduled = true;
|
|
62
|
-
this.abortController = new AbortController();
|
|
63
|
-
const signal = this.abortController.signal;
|
|
64
|
-
try {
|
|
65
|
-
while (this.isExecuting) {
|
|
66
|
-
await this.delay(this.options.wait, signal);
|
|
67
|
-
}
|
|
68
|
-
while (Date.now() < this.nextExecutionTime) {
|
|
69
|
-
await this.delay(this.nextExecutionTime - Date.now(), signal);
|
|
70
|
-
}
|
|
71
|
-
this.isScheduled = false;
|
|
72
|
-
this.isExecuting = true;
|
|
73
|
-
await this.executeFunction(...this.lastArgs);
|
|
74
|
-
} catch (error) {
|
|
75
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
76
|
-
return;
|
|
77
|
-
}
|
|
78
|
-
try {
|
|
79
|
-
this.options.onError(error);
|
|
80
|
-
} catch {
|
|
81
|
-
}
|
|
82
|
-
} finally {
|
|
83
|
-
this.nextExecutionTime = Date.now() + this.options.wait;
|
|
84
|
-
this.isExecuting = false;
|
|
85
|
-
this.abortController = null;
|
|
86
|
-
}
|
|
112
|
+
getLastExecutionTime() {
|
|
113
|
+
return this._lastExecutionTime;
|
|
87
114
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
() => {
|
|
94
|
-
clearTimeout(timeout);
|
|
95
|
-
reject(new Error("AbortError"));
|
|
96
|
-
},
|
|
97
|
-
{ once: true }
|
|
98
|
-
);
|
|
99
|
-
});
|
|
115
|
+
/**
|
|
116
|
+
* Returns the next execution time
|
|
117
|
+
*/
|
|
118
|
+
getNextExecutionTime() {
|
|
119
|
+
return this._nextExecutionTime;
|
|
100
120
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
121
|
+
/**
|
|
122
|
+
* Returns the last result of the debounced function
|
|
123
|
+
*/
|
|
124
|
+
getLastResult() {
|
|
125
|
+
return this._lastResult;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Returns the number of times the function has been executed successfully
|
|
129
|
+
*/
|
|
130
|
+
getSuccessCount() {
|
|
131
|
+
return this._successCount;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Returns the number of times the function has settled (completed or errored)
|
|
135
|
+
*/
|
|
136
|
+
getSettleCount() {
|
|
137
|
+
return this._settleCount;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Returns the number of times the function has errored
|
|
141
|
+
*/
|
|
142
|
+
getErrorCount() {
|
|
143
|
+
return this._errorCount;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Returns the current pending state
|
|
147
|
+
*/
|
|
148
|
+
getIsPending() {
|
|
149
|
+
return this._options.enabled && !!this._timeoutId;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Returns the current executing state
|
|
153
|
+
*/
|
|
154
|
+
getIsExecuting() {
|
|
155
|
+
return this._isExecuting;
|
|
105
156
|
}
|
|
106
157
|
}
|
|
107
158
|
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 * Time window in milliseconds during which the function can only be executed once\n * Defaults to 0ms\n */\n wait: number\n /**\n * Optional error handler for when the throttled function throws\n */\n onError?: (error: unknown) => void\n}\n\nconst defaultOptions: Required<AsyncThrottlerOptions> = {\n enabled: true,\n onError: () => {},\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 (...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 isScheduled = false\n private lastArgs: TArgs | undefined\n private nextExecutionTime = 0\n private options: Required<AsyncThrottlerOptions>\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncThrottlerOptions,\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>,\n ): Required<AsyncThrottlerOptions> {\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 * Returns the next execution time\n */\n getNextExecutionTime(): number {\n return this.nextExecutionTime\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.isScheduled = false\n this.lastArgs = undefined\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.isScheduled) return\n this.isScheduled = 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.isScheduled = 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.nextExecutionTime = Date.now() + 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 }\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 (...args: Array<any>) => Promise<any>,\n>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions, 'enabled'>) {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n return asyncThrottler.maybeExecute.bind(asyncThrottler)\n}\n"],"names":[],"mappings":"AAoBA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,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MAAM,SAAS,cAAc;AACzD;AAAA,MAAA;AAEE,UAAA;AACG,aAAA,QAAQ,QAAQ,KAAK;AAAA,MAAA,QACpB;AAAA,MAAA;AAAA,IAER,UACA;AACA,WAAK,oBAAoB,KAAK,IAAI,IAAI,KAAK,QAAQ;AACnD,WAAK,cAAc;AACnB,WAAK,kBAAkB;AAAA,IAAA;AAAA,EACzB;AAAA,EAGM,MAAM,IAAY,QAAoC;AAC5D,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AAChC,YAAA,UAAU,WAAW,SAAS,EAAE;AAC/B,aAAA;AAAA,QACL;AAAA,QACA,MAAM;AACJ,uBAAa,OAAO;AACb,iBAAA,IAAI,MAAM,YAAY,CAAC;AAAA,QAChC;AAAA,QACA,EAAE,MAAM,KAAK;AAAA,MACf;AAAA,IAAA,CACD;AAAA,EAAA;AAAA,EAGH,MAAc,mBAAmB,MAA4B;AACvD,QAAA,CAAC,KAAK,QAAQ,QAAS;AACtB,SAAA;AACC,UAAA,KAAK,GAAG,GAAG,IAAI;AAAA,EAAA;AAEzB;AAkBgB,SAAA,cAEd,IAAS,gBAAwD;AACjE,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;"}
|
|
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<TFn extends AnyAsyncFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute the function immediately when called\n * Defaults to true\n */\n leading?: boolean\n /**\n * Optional error handler for when the throttled function throws\n */\n onError?: (error: unknown, asyncThrottler: AsyncThrottler<TFn>) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onSettled?: (asyncThrottler: AsyncThrottler<TFn>) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n asyncThrottler: AsyncThrottler<TFn>,\n ) => void\n /**\n * Whether to execute the function on the trailing edge of the wait period\n * Defaults to true\n */\n trailing?: boolean\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>> = {\n enabled: true,\n leading: true,\n onError: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n trailing: true,\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<TFn extends AnyAsyncFunction> {\n private _options: Required<AsyncThrottlerOptions<TFn>>\n private _abortController: AbortController | null = null\n private _errorCount = 0\n private _isExecuting = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastExecutionTime = 0\n private _lastResult: ReturnType<TFn> | undefined\n private _nextExecutionTime = 0\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the throttler options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this.cancel()\n }\n }\n\n /**\n * Returns the current options\n */\n getOptions(): Required<AsyncThrottlerOptions<TFn>> {\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(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n const now = Date.now()\n const timeSinceLastExecution = now - this._lastExecutionTime\n\n // Handle leading execution\n if (this._options.leading && timeSinceLastExecution >= this._options.wait) {\n await this.executeFunction(...args)\n return this._lastResult\n } else {\n // Store the most recent arguments for potential trailing execution\n this._lastArgs = args\n\n return new Promise((resolve) => {\n // Clear any existing timeout to ensure we use the latest arguments\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n }\n\n // Set up trailing execution if enabled\n if (this._options.trailing) {\n const _timeSinceLastExecution = this._lastExecutionTime\n ? now - this._lastExecutionTime\n : 0\n const timeoutDuration = this._options.wait - _timeSinceLastExecution\n this._timeoutId = setTimeout(async () => {\n if (this._lastArgs !== undefined) {\n await this.executeFunction(...this._lastArgs)\n }\n resolve(this._lastResult)\n }, timeoutDuration)\n }\n })\n }\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled || this._isExecuting) 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._settleCount++\n this._abortController = null\n this._lastExecutionTime = Date.now()\n this._nextExecutionTime = this._lastExecutionTime + this._options.wait\n this._options.onSettled(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\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 }\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 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 the current pending state\n */\n getIsPending(): boolean {\n return this._options.enabled && !!this._timeoutId\n }\n\n /**\n * Returns the current executing state\n */\n getIsExecuting(): boolean {\n return this._isExecuting\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<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: Omit<AsyncThrottlerOptions<TFn>, 'enabled'>,\n) {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n return asyncThrottler.maybeExecute.bind(asyncThrottler)\n}\n"],"names":[],"mappings":"AA2CA,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;AAZV,SAAQ,mBAA2C;AACnD,SAAQ,cAAc;AACtB,SAAQ,eAA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AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAkBgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;"}
|
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> {
|
|
5
6
|
/**
|
|
6
7
|
* Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
7
8
|
* Defaults to true.
|
|
@@ -9,9 +10,14 @@ export interface DebouncerOptions {
|
|
|
9
10
|
enabled?: boolean;
|
|
10
11
|
/**
|
|
11
12
|
* Whether to execute on the leading edge of the timeout.
|
|
13
|
+
* The first call will execute immediately and the rest will wait the delay.
|
|
12
14
|
* Defaults to false.
|
|
13
15
|
*/
|
|
14
16
|
leading?: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* Callback function that is called after the function is executed
|
|
19
|
+
*/
|
|
20
|
+
onExecute?: (debouncer: Debouncer<TFn>) => void;
|
|
15
21
|
/**
|
|
16
22
|
* Whether to execute on the trailing edge of the timeout.
|
|
17
23
|
* Defaults to true.
|
|
@@ -46,32 +52,41 @@ export interface DebouncerOptions {
|
|
|
46
52
|
* });
|
|
47
53
|
* ```
|
|
48
54
|
*/
|
|
49
|
-
export declare class Debouncer<TFn extends
|
|
55
|
+
export declare class Debouncer<TFn extends AnyFunction> {
|
|
50
56
|
private fn;
|
|
51
|
-
private
|
|
52
|
-
private
|
|
53
|
-
private
|
|
54
|
-
private
|
|
55
|
-
|
|
57
|
+
private _canLeadingExecute;
|
|
58
|
+
private _executionCount;
|
|
59
|
+
private _isPending;
|
|
60
|
+
private _options;
|
|
61
|
+
private _timeoutId;
|
|
62
|
+
constructor(fn: TFn, initialOptions: DebouncerOptions<TFn>);
|
|
56
63
|
/**
|
|
57
64
|
* Updates the debouncer options
|
|
58
65
|
* Returns the new options state
|
|
59
66
|
*/
|
|
60
|
-
setOptions(newOptions: Partial<DebouncerOptions
|
|
67
|
+
setOptions(newOptions: Partial<DebouncerOptions<TFn>>): void;
|
|
61
68
|
/**
|
|
62
|
-
* Returns the
|
|
69
|
+
* Returns the current debouncer options
|
|
63
70
|
*/
|
|
64
|
-
|
|
71
|
+
getOptions(): Required<DebouncerOptions<TFn>>;
|
|
65
72
|
/**
|
|
66
73
|
* Attempts to execute the debounced function
|
|
67
74
|
* If a call is already in progress, it will be queued
|
|
68
75
|
*/
|
|
69
|
-
maybeExecute(...args:
|
|
76
|
+
maybeExecute(...args: Parameters<TFn>): void;
|
|
70
77
|
private executeFunction;
|
|
71
78
|
/**
|
|
72
79
|
* Cancels any pending execution
|
|
73
80
|
*/
|
|
74
81
|
cancel(): void;
|
|
82
|
+
/**
|
|
83
|
+
* Returns the number of times the function has been executed
|
|
84
|
+
*/
|
|
85
|
+
getExecutionCount(): number;
|
|
86
|
+
/**
|
|
87
|
+
* Returns `true` if debouncing
|
|
88
|
+
*/
|
|
89
|
+
getIsPending(): boolean;
|
|
75
90
|
}
|
|
76
91
|
/**
|
|
77
92
|
* Creates a debounced function that delays invoking the provided function until after a specified wait time.
|
|
@@ -93,4 +108,4 @@ export declare class Debouncer<TFn extends (...args: Array<any>) => any, TArgs e
|
|
|
93
108
|
* inputElement.addEventListener('input', debounced);
|
|
94
109
|
* ```
|
|
95
110
|
*/
|
|
96
|
-
export declare function debounce<TFn extends
|
|
111
|
+
export declare function debounce<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<DebouncerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => void;
|
package/dist/esm/debouncer.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
const defaultOptions = {
|
|
2
2
|
enabled: true,
|
|
3
3
|
leading: false,
|
|
4
|
+
onExecute: () => {
|
|
5
|
+
},
|
|
4
6
|
trailing: true,
|
|
5
7
|
wait: 0
|
|
6
8
|
};
|
|
7
9
|
class Debouncer {
|
|
8
10
|
constructor(fn, initialOptions) {
|
|
9
11
|
this.fn = fn;
|
|
10
|
-
this.
|
|
11
|
-
this.
|
|
12
|
-
this.
|
|
12
|
+
this._canLeadingExecute = true;
|
|
13
|
+
this._executionCount = 0;
|
|
14
|
+
this._isPending = false;
|
|
15
|
+
this._options = {
|
|
13
16
|
...defaultOptions,
|
|
14
17
|
...initialOptions
|
|
15
18
|
};
|
|
@@ -19,49 +22,68 @@ class Debouncer {
|
|
|
19
22
|
* Returns the new options state
|
|
20
23
|
*/
|
|
21
24
|
setOptions(newOptions) {
|
|
22
|
-
this.
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}
|
|
26
|
-
return this.options;
|
|
25
|
+
this._options = { ...this._options, ...newOptions };
|
|
26
|
+
if (!this._options.enabled) {
|
|
27
|
+
this._isPending = false;
|
|
28
|
+
}
|
|
27
29
|
}
|
|
28
30
|
/**
|
|
29
|
-
* Returns the
|
|
31
|
+
* Returns the current debouncer options
|
|
30
32
|
*/
|
|
31
|
-
|
|
32
|
-
return this.
|
|
33
|
+
getOptions() {
|
|
34
|
+
return this._options;
|
|
33
35
|
}
|
|
34
36
|
/**
|
|
35
37
|
* Attempts to execute the debounced function
|
|
36
38
|
* If a call is already in progress, it will be queued
|
|
37
39
|
*/
|
|
38
40
|
maybeExecute(...args) {
|
|
39
|
-
|
|
41
|
+
let _didLeadingExecute = false;
|
|
42
|
+
if (this._options.leading && this._canLeadingExecute) {
|
|
43
|
+
this._canLeadingExecute = false;
|
|
44
|
+
_didLeadingExecute = true;
|
|
40
45
|
this.executeFunction(...args);
|
|
41
|
-
this.canLeadingExecute = false;
|
|
42
46
|
}
|
|
43
|
-
if (this.
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
if (this._options.trailing) {
|
|
48
|
+
this._isPending = true;
|
|
49
|
+
}
|
|
50
|
+
if (this._timeoutId) clearTimeout(this._timeoutId);
|
|
51
|
+
this._timeoutId = setTimeout(() => {
|
|
52
|
+
this._canLeadingExecute = true;
|
|
53
|
+
if (this._options.trailing && !_didLeadingExecute) {
|
|
47
54
|
this.executeFunction(...args);
|
|
48
55
|
}
|
|
49
|
-
}, this.
|
|
56
|
+
}, this._options.wait);
|
|
50
57
|
}
|
|
51
58
|
executeFunction(...args) {
|
|
52
|
-
if (!this.
|
|
53
|
-
this.executionCount++;
|
|
59
|
+
if (!this._options.enabled) return void 0;
|
|
54
60
|
this.fn(...args);
|
|
61
|
+
this._isPending = false;
|
|
62
|
+
this._executionCount++;
|
|
63
|
+
this._options.onExecute(this);
|
|
55
64
|
}
|
|
56
65
|
/**
|
|
57
66
|
* Cancels any pending execution
|
|
58
67
|
*/
|
|
59
68
|
cancel() {
|
|
60
|
-
if (this.
|
|
61
|
-
clearTimeout(this.
|
|
62
|
-
this.
|
|
69
|
+
if (this._timeoutId) {
|
|
70
|
+
clearTimeout(this._timeoutId);
|
|
71
|
+
this._canLeadingExecute = true;
|
|
72
|
+
this._isPending = false;
|
|
63
73
|
}
|
|
64
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* Returns the number of times the function has been executed
|
|
77
|
+
*/
|
|
78
|
+
getExecutionCount() {
|
|
79
|
+
return this._executionCount;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Returns `true` if debouncing
|
|
83
|
+
*/
|
|
84
|
+
getIsPending() {
|
|
85
|
+
return this._options.enabled && this._isPending;
|
|
86
|
+
}
|
|
65
87
|
}
|
|
66
88
|
function debounce(fn, initialOptions) {
|
|
67
89
|
const debouncer = new Debouncer(fn, initialOptions);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debouncer.js","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.js","sources":["../../src/debouncer.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\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 * The first call will execute immediately and the rest will wait the delay.\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>) => 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>> = {\n enabled: true,\n leading: false,\n onExecute: () => {},\n trailing: true,\n wait: 0,\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> {\n private _canLeadingExecute = true\n private _executionCount = 0\n private _isPending = false\n private _options: Required<DebouncerOptions<TFn>>\n private _timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: DebouncerOptions<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<DebouncerOptions<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<DebouncerOptions<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 maybeExecute(...args: Parameters<TFn>): void {\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n _didLeadingExecute = true\n this.executeFunction(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (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 and execute trailing only if enabled and did not execute leading\n this._timeoutId = setTimeout(() => {\n this._canLeadingExecute = true\n if (this._options.trailing && !_didLeadingExecute) {\n this.executeFunction(...args)\n }\n }, this._options.wait)\n }\n\n private executeFunction(...args: Parameters<TFn>): void {\n if (!this._options.enabled) return undefined\n this.fn(...args) // EXECUTE!\n this._isPending = false\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>, 'enabled'>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute.bind(debouncer)\n}\n"],"names":[],"mappings":"AAiCA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AAyBO,MAAM,UAAmC;AAAA,EAO9C,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAQ,qBAAqB;AAC7B,SAAQ,kBAAkB;AAC1B,SAAQ,aAAa;AAQnB,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAkD;AAC3D,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAG9C,QAAA,CAAC,KAAK,SAAS,SAAS;AAC1B,WAAK,aAAa;AAAA,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAMF,aAA8C;AAC5C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,gBAAgB,MAA6B;AAC3C,QAAI,qBAAqB;AAGzB,QAAI,KAAK,SAAS,WAAW,KAAK,oBAAoB;AACpD,WAAK,qBAAqB;AACL,2BAAA;AAChB,WAAA,gBAAgB,GAAG,IAAI;AAAA,IAAA;AAI1B,QAAA,KAAK,SAAS,UAAU;AAC1B,WAAK,aAAa;AAAA,IAAA;AAIpB,QAAI,KAAK,WAAyB,cAAA,KAAK,UAAU;AAG5C,SAAA,aAAa,WAAW,MAAM;AACjC,WAAK,qBAAqB;AAC1B,UAAI,KAAK,SAAS,YAAY,CAAC,oBAAoB;AAC5C,aAAA,gBAAgB,GAAG,IAAI;AAAA,MAAA;AAAA,IAC9B,GACC,KAAK,SAAS,IAAI;AAAA,EAAA;AAAA,EAGf,mBAAmB,MAA6B;AACtD,QAAI,CAAC,KAAK,SAAS,QAAgB,QAAA;AAC9B,SAAA,GAAG,GAAG,IAAI;AACf,SAAK,aAAa;AACb,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,gBACoC;AACpC,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;"}
|
package/dist/esm/index.d.ts
CHANGED
package/dist/esm/index.js
CHANGED
|
@@ -7,6 +7,7 @@ import { Debouncer, debounce } from "./debouncer.js";
|
|
|
7
7
|
import { Queuer, queue } from "./queuer.js";
|
|
8
8
|
import { RateLimiter, rateLimit } from "./rate-limiter.js";
|
|
9
9
|
import { Throttler, throttle } from "./throttler.js";
|
|
10
|
+
import { bindInstanceMethods } from "./utils.js";
|
|
10
11
|
export {
|
|
11
12
|
AsyncDebouncer,
|
|
12
13
|
AsyncQueuer,
|
|
@@ -20,6 +21,7 @@ export {
|
|
|
20
21
|
asyncQueue,
|
|
21
22
|
asyncRateLimit,
|
|
22
23
|
asyncThrottle,
|
|
24
|
+
bindInstanceMethods,
|
|
23
25
|
debounce,
|
|
24
26
|
isPlainArray,
|
|
25
27
|
isPlainObject,
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"}
|