@tanstack/pacer 0.2.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 +78 -45
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +44 -16
- package/dist/cjs/async-queuer.cjs +53 -3
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +28 -3
- package/dist/cjs/async-rate-limiter.cjs +46 -35
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +34 -19
- package/dist/cjs/async-throttler.cjs +85 -57
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +49 -17
- package/dist/cjs/debouncer.cjs +12 -14
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +10 -9
- package/dist/cjs/queuer.cjs +51 -1
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +30 -1
- package/dist/cjs/rate-limiter.cjs +1 -5
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +9 -9
- package/dist/cjs/throttler.cjs +29 -36
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +16 -17
- package/dist/cjs/types.d.cts +2 -6
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +1 -1
- package/dist/esm/async-debouncer.d.ts +44 -16
- package/dist/esm/async-debouncer.js +78 -45
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +28 -3
- package/dist/esm/async-queuer.js +53 -3
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +34 -19
- package/dist/esm/async-rate-limiter.js +46 -35
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +49 -17
- package/dist/esm/async-throttler.js +85 -57
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/debouncer.d.ts +10 -9
- package/dist/esm/debouncer.js +12 -14
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/queuer.d.ts +30 -1
- package/dist/esm/queuer.js +51 -1
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +9 -9
- package/dist/esm/rate-limiter.js +1 -5
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +16 -17
- package/dist/esm/throttler.js +29 -36
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/types.d.ts +2 -6
- package/dist/esm/utils.d.ts +1 -1
- package/dist/esm/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/async-debouncer.ts +114 -73
- package/src/async-queuer.ts +93 -8
- package/src/async-rate-limiter.ts +74 -60
- package/src/async-throttler.ts +135 -86
- package/src/debouncer.ts +26 -33
- package/src/queuer.ts +92 -4
- package/src/rate-limiter.ts +14 -26
- package/src/throttler.ts +45 -53
- package/src/types.ts +2 -10
- package/src/utils.ts +1 -1
|
@@ -1 +1 @@
|
|
|
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,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A;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
|
+
{"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<TFn extends AnyAsyncFunction> {\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, rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n rateLimiter: AsyncRateLimiter<TFn>,\n ) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => 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>, 'limit' | 'window'>\n> = {\n enabled: true,\n onError: () => {},\n onReject: () => {},\n onSettled: () => {},\n onSuccess: () => {},\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<TFn extends AnyAsyncFunction> {\n private _options: AsyncRateLimiterOptions<TFn>\n private _errorCount = 0\n private _executionTimes: Array<number> = []\n private _lastResult: ReturnType<TFn> | undefined\n private _rejectionCount = 0\n private _settleCount = 0\n private _successCount = 0\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\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(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<AsyncRateLimiterOptions<TFn>> {\n return this._options as Required<AsyncRateLimiterOptions<TFn>>\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(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this.cleanupOldExecutions()\n\n if (this._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n this.rejectFunction()\n return undefined\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled) return\n const now = Date.now()\n this._executionTimes.push(now)\n\n try {\n this._lastResult = await this.fn(...args)\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._settleCount++\n this._options.onSettled?.(this)\n }\n\n return this._lastResult\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 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 * Returns the number of times the function has been executed\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has been settled\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 number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._successCount = 0\n this._errorCount = 0\n this._rejectionCount = 0\n this._settleCount = 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<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: Omit<AsyncRateLimiterOptions<TFn>, 'enabled'>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":"AAwCA,MAAM,iBAEF;AAAA,EACF,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAA;AACnB;AA2BO,MAAM,iBAA+C;AAAA,EAS1D,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AARV,SAAQ,cAAc;AACtB,SAAQ,k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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,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,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,gBAAgB;AACrB,SAAK,cAAc;AACnB,SAAK,kBAAkB;AACvB,SAAK,eAAe;AAAA,EAAA;AAExB;AAgCgB,SAAA,eACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;"}
|
|
@@ -2,20 +2,34 @@ import { AnyAsyncFunction } from './types.js';
|
|
|
2
2
|
/**
|
|
3
3
|
* Options for configuring an async throttled function
|
|
4
4
|
*/
|
|
5
|
-
export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction
|
|
5
|
+
export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
8
|
* Defaults to true.
|
|
9
9
|
*/
|
|
10
10
|
enabled?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Whether to execute the function immediately when called
|
|
13
|
+
* Defaults to true
|
|
14
|
+
*/
|
|
15
|
+
leading?: boolean;
|
|
11
16
|
/**
|
|
12
17
|
* Optional error handler for when the throttled function throws
|
|
13
18
|
*/
|
|
14
|
-
onError?: (error: unknown) => void;
|
|
19
|
+
onError?: (error: unknown, asyncThrottler: AsyncThrottler<TFn>) => void;
|
|
20
|
+
/**
|
|
21
|
+
* Optional function to call when the throttled function is executed
|
|
22
|
+
*/
|
|
23
|
+
onSettled?: (asyncThrottler: AsyncThrottler<TFn>) => void;
|
|
15
24
|
/**
|
|
16
25
|
* Optional function to call when the throttled function is executed
|
|
17
26
|
*/
|
|
18
|
-
|
|
27
|
+
onSuccess?: (result: ReturnType<TFn>, asyncThrottler: AsyncThrottler<TFn>) => void;
|
|
28
|
+
/**
|
|
29
|
+
* Whether to execute the function on the trailing edge of the wait period
|
|
30
|
+
* Defaults to true
|
|
31
|
+
*/
|
|
32
|
+
trailing?: boolean;
|
|
19
33
|
/**
|
|
20
34
|
* Time window in milliseconds during which the function can only be executed once
|
|
21
35
|
* Defaults to 0ms
|
|
@@ -44,41 +58,39 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction, TArgs exten
|
|
|
44
58
|
* });
|
|
45
59
|
* ```
|
|
46
60
|
*/
|
|
47
|
-
export declare class AsyncThrottler<TFn extends AnyAsyncFunction
|
|
61
|
+
export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
|
|
48
62
|
private fn;
|
|
49
63
|
private _options;
|
|
50
64
|
private _abortController;
|
|
51
|
-
private
|
|
65
|
+
private _errorCount;
|
|
52
66
|
private _isExecuting;
|
|
53
|
-
private _isPending;
|
|
54
67
|
private _lastArgs;
|
|
55
68
|
private _lastExecutionTime;
|
|
69
|
+
private _lastResult;
|
|
56
70
|
private _nextExecutionTime;
|
|
57
|
-
|
|
71
|
+
private _settleCount;
|
|
72
|
+
private _successCount;
|
|
73
|
+
private _timeoutId;
|
|
74
|
+
constructor(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>);
|
|
58
75
|
/**
|
|
59
76
|
* Updates the throttler options
|
|
60
77
|
* Returns the new options state
|
|
61
78
|
*/
|
|
62
|
-
setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn
|
|
79
|
+
setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn>>): void;
|
|
63
80
|
/**
|
|
64
81
|
* Returns the current options
|
|
65
82
|
*/
|
|
66
|
-
getOptions(): Required<AsyncThrottlerOptions<TFn
|
|
83
|
+
getOptions(): Required<AsyncThrottlerOptions<TFn>>;
|
|
67
84
|
/**
|
|
68
85
|
* Attempts to execute the throttled function
|
|
69
86
|
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
70
87
|
*/
|
|
71
|
-
maybeExecute(...args:
|
|
72
|
-
private delay;
|
|
88
|
+
maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
|
|
73
89
|
private executeFunction;
|
|
74
90
|
/**
|
|
75
|
-
* Cancels any pending execution
|
|
91
|
+
* Cancels any pending execution or aborts any execution in progress
|
|
76
92
|
*/
|
|
77
93
|
cancel(): void;
|
|
78
|
-
/**
|
|
79
|
-
* Returns the number of times the function has been executed
|
|
80
|
-
*/
|
|
81
|
-
getExecutionCount(): number;
|
|
82
94
|
/**
|
|
83
95
|
* Returns the last execution time
|
|
84
96
|
*/
|
|
@@ -87,10 +99,30 @@ export declare class AsyncThrottler<TFn extends AnyAsyncFunction, TArgs extends
|
|
|
87
99
|
* Returns the next execution time
|
|
88
100
|
*/
|
|
89
101
|
getNextExecutionTime(): number;
|
|
102
|
+
/**
|
|
103
|
+
* Returns the last result of the debounced function
|
|
104
|
+
*/
|
|
105
|
+
getLastResult(): ReturnType<TFn> | undefined;
|
|
106
|
+
/**
|
|
107
|
+
* Returns the number of times the function has been executed successfully
|
|
108
|
+
*/
|
|
109
|
+
getSuccessCount(): number;
|
|
110
|
+
/**
|
|
111
|
+
* Returns the number of times the function has settled (completed or errored)
|
|
112
|
+
*/
|
|
113
|
+
getSettleCount(): number;
|
|
114
|
+
/**
|
|
115
|
+
* Returns the number of times the function has errored
|
|
116
|
+
*/
|
|
117
|
+
getErrorCount(): number;
|
|
90
118
|
/**
|
|
91
119
|
* Returns the current pending state
|
|
92
120
|
*/
|
|
93
121
|
getIsPending(): boolean;
|
|
122
|
+
/**
|
|
123
|
+
* Returns the current executing state
|
|
124
|
+
*/
|
|
125
|
+
getIsExecuting(): boolean;
|
|
94
126
|
}
|
|
95
127
|
/**
|
|
96
128
|
* Creates an async throttled function that limits how often the function can execute.
|
|
@@ -108,4 +140,4 @@ export declare class AsyncThrottler<TFn extends AnyAsyncFunction, TArgs extends
|
|
|
108
140
|
* await throttled(); // Waits 1 second before executing
|
|
109
141
|
* ```
|
|
110
142
|
*/
|
|
111
|
-
export declare function asyncThrottle<TFn extends AnyAsyncFunction
|
|
143
|
+
export declare function asyncThrottle<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
|
|
@@ -1,20 +1,26 @@
|
|
|
1
1
|
const defaultOptions = {
|
|
2
2
|
enabled: true,
|
|
3
|
+
leading: true,
|
|
3
4
|
onError: () => {
|
|
4
5
|
},
|
|
5
|
-
|
|
6
|
+
onSettled: () => {
|
|
6
7
|
},
|
|
8
|
+
onSuccess: () => {
|
|
9
|
+
},
|
|
10
|
+
trailing: true,
|
|
7
11
|
wait: 0
|
|
8
12
|
};
|
|
9
13
|
class AsyncThrottler {
|
|
10
14
|
constructor(fn, initialOptions) {
|
|
11
15
|
this.fn = fn;
|
|
12
16
|
this._abortController = null;
|
|
13
|
-
this.
|
|
17
|
+
this._errorCount = 0;
|
|
14
18
|
this._isExecuting = false;
|
|
15
|
-
this._isPending = false;
|
|
16
19
|
this._lastExecutionTime = 0;
|
|
17
20
|
this._nextExecutionTime = 0;
|
|
21
|
+
this._settleCount = 0;
|
|
22
|
+
this._successCount = 0;
|
|
23
|
+
this._timeoutId = null;
|
|
18
24
|
this._options = {
|
|
19
25
|
...defaultOptions,
|
|
20
26
|
...initialOptions
|
|
@@ -25,11 +31,10 @@ class AsyncThrottler {
|
|
|
25
31
|
* Returns the new options state
|
|
26
32
|
*/
|
|
27
33
|
setOptions(newOptions) {
|
|
28
|
-
this._options = {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
}
|
|
32
|
-
return this._options;
|
|
34
|
+
this._options = { ...this._options, ...newOptions };
|
|
35
|
+
if (!this._options.enabled) {
|
|
36
|
+
this.cancel();
|
|
37
|
+
}
|
|
33
38
|
}
|
|
34
39
|
/**
|
|
35
40
|
* Returns the current options
|
|
@@ -42,72 +47,65 @@ class AsyncThrottler {
|
|
|
42
47
|
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
43
48
|
*/
|
|
44
49
|
async maybeExecute(...args) {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
this.
|
|
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;
|
|
48
76
|
this._abortController = new AbortController();
|
|
49
|
-
const signal = this._abortController.signal;
|
|
50
77
|
try {
|
|
51
|
-
while (this._isExecuting) {
|
|
52
|
-
await this.delay(this._options.wait, signal);
|
|
53
|
-
}
|
|
54
|
-
while (Date.now() < this._nextExecutionTime) {
|
|
55
|
-
await this.delay(this._nextExecutionTime - Date.now(), signal);
|
|
56
|
-
}
|
|
57
|
-
this._isPending = false;
|
|
58
78
|
this._isExecuting = true;
|
|
59
|
-
await this.
|
|
79
|
+
this._lastResult = await this.fn(...args);
|
|
80
|
+
this._successCount++;
|
|
81
|
+
this._options.onSuccess(this._lastResult, this);
|
|
60
82
|
} catch (error) {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}
|
|
64
|
-
try {
|
|
65
|
-
this._options.onError(error);
|
|
66
|
-
} catch {
|
|
67
|
-
}
|
|
83
|
+
this._errorCount++;
|
|
84
|
+
this._options.onError(error, this);
|
|
68
85
|
} finally {
|
|
69
|
-
this._lastExecutionTime = Date.now();
|
|
70
|
-
this._nextExecutionTime = this._lastExecutionTime + this._options.wait;
|
|
71
86
|
this._isExecuting = false;
|
|
87
|
+
this._settleCount++;
|
|
72
88
|
this._abortController = null;
|
|
89
|
+
this._lastExecutionTime = Date.now();
|
|
90
|
+
this._nextExecutionTime = this._lastExecutionTime + this._options.wait;
|
|
91
|
+
this._options.onSettled(this);
|
|
73
92
|
}
|
|
74
|
-
|
|
75
|
-
delay(ms, signal) {
|
|
76
|
-
return new Promise((resolve, reject) => {
|
|
77
|
-
const timeout = setTimeout(resolve, ms);
|
|
78
|
-
signal.addEventListener(
|
|
79
|
-
"abort",
|
|
80
|
-
() => {
|
|
81
|
-
clearTimeout(timeout);
|
|
82
|
-
reject(new Error("AbortError"));
|
|
83
|
-
},
|
|
84
|
-
{ once: true }
|
|
85
|
-
);
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
async executeFunction(...args) {
|
|
89
|
-
if (!this._options.enabled) return;
|
|
90
|
-
this._executionCount++;
|
|
91
|
-
await this.fn(...args);
|
|
92
|
-
this._options.onExecute(this);
|
|
93
|
+
return this._lastResult;
|
|
93
94
|
}
|
|
94
95
|
/**
|
|
95
|
-
* Cancels any pending execution
|
|
96
|
+
* Cancels any pending execution or aborts any execution in progress
|
|
96
97
|
*/
|
|
97
98
|
cancel() {
|
|
99
|
+
if (this._timeoutId) {
|
|
100
|
+
clearTimeout(this._timeoutId);
|
|
101
|
+
this._timeoutId = null;
|
|
102
|
+
}
|
|
98
103
|
if (this._abortController) {
|
|
99
104
|
this._abortController.abort();
|
|
100
105
|
this._abortController = null;
|
|
101
106
|
}
|
|
102
|
-
this._isPending = false;
|
|
103
107
|
this._lastArgs = void 0;
|
|
104
108
|
}
|
|
105
|
-
/**
|
|
106
|
-
* Returns the number of times the function has been executed
|
|
107
|
-
*/
|
|
108
|
-
getExecutionCount() {
|
|
109
|
-
return this._executionCount;
|
|
110
|
-
}
|
|
111
109
|
/**
|
|
112
110
|
* Returns the last execution time
|
|
113
111
|
*/
|
|
@@ -120,11 +118,41 @@ class AsyncThrottler {
|
|
|
120
118
|
getNextExecutionTime() {
|
|
121
119
|
return this._nextExecutionTime;
|
|
122
120
|
}
|
|
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
|
+
}
|
|
123
145
|
/**
|
|
124
146
|
* Returns the current pending state
|
|
125
147
|
*/
|
|
126
148
|
getIsPending() {
|
|
127
|
-
return this.
|
|
149
|
+
return this._options.enabled && !!this._timeoutId;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Returns the current executing state
|
|
153
|
+
*/
|
|
154
|
+
getIsExecuting() {
|
|
155
|
+
return this._isExecuting;
|
|
128
156
|
}
|
|
129
157
|
}
|
|
130
158
|
function asyncThrottle(fn, initialOptions) {
|
|
@@ -1 +1 @@
|
|
|
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":"AA6BA,MAAM,iBAA4D;AAAA,EAChE,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAC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,WAAK,eAAe;AACpB,WAAK,mBAAmB;AAAA,IAAA;AAAA,EAC1B;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,SAAS,QAAS;AACvB,SAAA;AACC,UAAA,KAAK,GAAG,GAAG,IAAI;AAChB,SAAA,SAAS,UAAU,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM9B,SAAe;AACb,QAAI,KAAK,kBAAkB;AACzB,WAAK,iBAAiB,MAAM;AAC5B,WAAK,mBAAmB;AAAA,IAAA;AAE1B,SAAK,aAAa;AAClB,SAAK,YAAY;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMnB,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,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
|
+
{"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,EA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B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACtB,WAAO,KAAK,SAAS,WAAW,CAAC,CAAC,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMzC,iBAA0B;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
|
@@ -2,7 +2,7 @@ import { AnyFunction } from './types.js';
|
|
|
2
2
|
/**
|
|
3
3
|
* Options for configuring a debounced function
|
|
4
4
|
*/
|
|
5
|
-
export interface DebouncerOptions<TFn extends AnyFunction
|
|
5
|
+
export interface DebouncerOptions<TFn extends AnyFunction> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
8
|
* Defaults to true.
|
|
@@ -10,13 +10,14 @@ export interface DebouncerOptions<TFn extends AnyFunction, TArgs extends Paramet
|
|
|
10
10
|
enabled?: boolean;
|
|
11
11
|
/**
|
|
12
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.
|
|
13
14
|
* Defaults to false.
|
|
14
15
|
*/
|
|
15
16
|
leading?: boolean;
|
|
16
17
|
/**
|
|
17
18
|
* Callback function that is called after the function is executed
|
|
18
19
|
*/
|
|
19
|
-
onExecute?: (debouncer: Debouncer<TFn
|
|
20
|
+
onExecute?: (debouncer: Debouncer<TFn>) => void;
|
|
20
21
|
/**
|
|
21
22
|
* Whether to execute on the trailing edge of the timeout.
|
|
22
23
|
* Defaults to true.
|
|
@@ -51,28 +52,28 @@ export interface DebouncerOptions<TFn extends AnyFunction, TArgs extends Paramet
|
|
|
51
52
|
* });
|
|
52
53
|
* ```
|
|
53
54
|
*/
|
|
54
|
-
export declare class Debouncer<TFn extends AnyFunction
|
|
55
|
+
export declare class Debouncer<TFn extends AnyFunction> {
|
|
55
56
|
private fn;
|
|
56
57
|
private _canLeadingExecute;
|
|
57
|
-
private _isPending;
|
|
58
58
|
private _executionCount;
|
|
59
|
+
private _isPending;
|
|
59
60
|
private _options;
|
|
60
61
|
private _timeoutId;
|
|
61
|
-
constructor(fn: TFn, initialOptions: DebouncerOptions<TFn
|
|
62
|
+
constructor(fn: TFn, initialOptions: DebouncerOptions<TFn>);
|
|
62
63
|
/**
|
|
63
64
|
* Updates the debouncer options
|
|
64
65
|
* Returns the new options state
|
|
65
66
|
*/
|
|
66
|
-
setOptions(newOptions: Partial<DebouncerOptions<TFn
|
|
67
|
+
setOptions(newOptions: Partial<DebouncerOptions<TFn>>): void;
|
|
67
68
|
/**
|
|
68
69
|
* Returns the current debouncer options
|
|
69
70
|
*/
|
|
70
|
-
getOptions(): Required<DebouncerOptions<TFn
|
|
71
|
+
getOptions(): Required<DebouncerOptions<TFn>>;
|
|
71
72
|
/**
|
|
72
73
|
* Attempts to execute the debounced function
|
|
73
74
|
* If a call is already in progress, it will be queued
|
|
74
75
|
*/
|
|
75
|
-
maybeExecute(...args:
|
|
76
|
+
maybeExecute(...args: Parameters<TFn>): void;
|
|
76
77
|
private executeFunction;
|
|
77
78
|
/**
|
|
78
79
|
* Cancels any pending execution
|
|
@@ -107,4 +108,4 @@ export declare class Debouncer<TFn extends AnyFunction, TArgs extends Parameters
|
|
|
107
108
|
* inputElement.addEventListener('input', debounced);
|
|
108
109
|
* ```
|
|
109
110
|
*/
|
|
110
|
-
export declare function debounce<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<DebouncerOptions<TFn
|
|
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,17 +1,17 @@
|
|
|
1
1
|
const defaultOptions = {
|
|
2
2
|
enabled: true,
|
|
3
3
|
leading: false,
|
|
4
|
-
trailing: true,
|
|
5
|
-
wait: 0,
|
|
6
4
|
onExecute: () => {
|
|
7
|
-
}
|
|
5
|
+
},
|
|
6
|
+
trailing: true,
|
|
7
|
+
wait: 0
|
|
8
8
|
};
|
|
9
9
|
class Debouncer {
|
|
10
10
|
constructor(fn, initialOptions) {
|
|
11
11
|
this.fn = fn;
|
|
12
12
|
this._canLeadingExecute = true;
|
|
13
|
-
this._isPending = false;
|
|
14
13
|
this._executionCount = 0;
|
|
14
|
+
this._isPending = false;
|
|
15
15
|
this._options = {
|
|
16
16
|
...defaultOptions,
|
|
17
17
|
...initialOptions
|
|
@@ -22,14 +22,10 @@ class Debouncer {
|
|
|
22
22
|
* Returns the new options state
|
|
23
23
|
*/
|
|
24
24
|
setOptions(newOptions) {
|
|
25
|
-
this._options = {
|
|
26
|
-
...this._options,
|
|
27
|
-
...newOptions
|
|
28
|
-
};
|
|
25
|
+
this._options = { ...this._options, ...newOptions };
|
|
29
26
|
if (!this._options.enabled) {
|
|
30
27
|
this._isPending = false;
|
|
31
28
|
}
|
|
32
|
-
return this._options;
|
|
33
29
|
}
|
|
34
30
|
/**
|
|
35
31
|
* Returns the current debouncer options
|
|
@@ -42,25 +38,27 @@ class Debouncer {
|
|
|
42
38
|
* If a call is already in progress, it will be queued
|
|
43
39
|
*/
|
|
44
40
|
maybeExecute(...args) {
|
|
41
|
+
let _didLeadingExecute = false;
|
|
45
42
|
if (this._options.leading && this._canLeadingExecute) {
|
|
46
|
-
this.executeFunction(...args);
|
|
47
43
|
this._canLeadingExecute = false;
|
|
44
|
+
_didLeadingExecute = true;
|
|
45
|
+
this.executeFunction(...args);
|
|
48
46
|
}
|
|
49
|
-
if (this._options.
|
|
47
|
+
if (this._options.trailing) {
|
|
50
48
|
this._isPending = true;
|
|
51
49
|
}
|
|
52
50
|
if (this._timeoutId) clearTimeout(this._timeoutId);
|
|
53
51
|
this._timeoutId = setTimeout(() => {
|
|
54
52
|
this._canLeadingExecute = true;
|
|
55
|
-
this.
|
|
56
|
-
if (this._options.trailing) {
|
|
53
|
+
if (this._options.trailing && !_didLeadingExecute) {
|
|
57
54
|
this.executeFunction(...args);
|
|
58
55
|
}
|
|
59
56
|
}, this._options.wait);
|
|
60
57
|
}
|
|
61
58
|
executeFunction(...args) {
|
|
62
|
-
if (!this._options.enabled) return;
|
|
59
|
+
if (!this._options.enabled) return void 0;
|
|
63
60
|
this.fn(...args);
|
|
61
|
+
this._isPending = false;
|
|
64
62
|
this._executionCount++;
|
|
65
63
|
this._options.onExecute(this);
|
|
66
64
|
}
|
|
@@ -1 +1 @@
|
|
|
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
|
|
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;AAA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