@tanstack/pacer 0.8.0 → 0.9.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-batcher.cjs +163 -0
- package/dist/cjs/async-batcher.cjs.map +1 -0
- package/dist/cjs/async-batcher.d.cts +273 -0
- package/dist/cjs/async-debouncer.cjs +149 -162
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +76 -57
- package/dist/cjs/async-queuer.cjs +282 -343
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +121 -100
- package/dist/cjs/async-rate-limiter.cjs +128 -185
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +72 -61
- package/dist/cjs/async-throttler.cjs +168 -178
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +97 -69
- package/dist/cjs/batcher.cjs +110 -119
- package/dist/cjs/batcher.cjs.map +1 -1
- package/dist/cjs/batcher.d.cts +76 -51
- package/dist/cjs/debouncer.cjs +97 -85
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +54 -26
- package/dist/cjs/index.cjs +3 -6
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +1 -1
- package/dist/cjs/queuer.cjs +246 -294
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +102 -81
- package/dist/cjs/rate-limiter.cjs +97 -130
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +50 -37
- package/dist/cjs/throttler.cjs +107 -123
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +59 -35
- package/dist/cjs/utils.cjs +0 -13
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +0 -1
- package/dist/esm/async-batcher.d.ts +273 -0
- package/dist/esm/async-batcher.js +163 -0
- package/dist/esm/async-batcher.js.map +1 -0
- package/dist/esm/async-debouncer.d.ts +76 -57
- package/dist/esm/async-debouncer.js +149 -162
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +121 -100
- package/dist/esm/async-queuer.js +282 -343
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +72 -61
- package/dist/esm/async-rate-limiter.js +128 -185
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +97 -69
- package/dist/esm/async-throttler.js +168 -178
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/batcher.d.ts +76 -51
- package/dist/esm/batcher.js +110 -119
- package/dist/esm/batcher.js.map +1 -1
- package/dist/esm/debouncer.d.ts +54 -26
- package/dist/esm/debouncer.js +97 -85
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +4 -7
- package/dist/esm/queuer.d.ts +102 -81
- package/dist/esm/queuer.js +246 -294
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +50 -37
- package/dist/esm/rate-limiter.js +97 -130
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +59 -35
- package/dist/esm/throttler.js +107 -123
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/utils.d.ts +0 -1
- package/dist/esm/utils.js +0 -13
- package/dist/esm/utils.js.map +1 -1
- package/package.json +14 -11
- package/src/async-batcher.ts +475 -0
- package/src/async-debouncer.ts +201 -121
- package/src/async-queuer.ts +337 -216
- package/src/async-rate-limiter.ts +176 -136
- package/src/async-throttler.ts +233 -139
- package/src/batcher.ts +158 -92
- package/src/debouncer.ts +135 -52
- package/src/index.ts +1 -1
- package/src/queuer.ts +348 -226
- package/src/rate-limiter.ts +125 -80
- package/src/throttler.ts +152 -78
- package/src/utils.ts +0 -15
- package/dist/cjs/compare.cjs +0 -72
- package/dist/cjs/compare.cjs.map +0 -1
- package/dist/cjs/compare.d.cts +0 -12
- package/dist/esm/compare.d.ts +0 -12
- package/dist/esm/compare.js +0 -72
- package/dist/esm/compare.js.map +0 -1
- package/src/compare.ts +0 -105
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limiter.cjs","sources":["../../src/rate-limiter.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n limit: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n window: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Required<RateLimiterOptions<any>> = {\n enabled: true,\n limit: 1,\n onExecute: () => {},\n onReject: () => {},\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a 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 * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\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 RateLimiter(\n * (id: string) => api.getData(id),\n * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n private _executionCount = 0\n private _rejectionCount = 0\n private _executionTimes: Array<number> = []\n private _options: RateLimiterOptions<TFn>\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n */\n setOptions(newOptions: Partial<RateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<RateLimiterOptions<TFn>> {\n return this._options as Required<RateLimiterOptions<TFn>>\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n getEnabled(): boolean {\n return parseFunctionOrValue(this._options.enabled, this)!\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n getLimit(): number {\n return parseFunctionOrValue(this._options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n getWindow(): number {\n return parseFunctionOrValue(this._options.window, this)\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 *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute(...args: Parameters<TFn>): boolean {\n this.cleanupOldExecutions()\n\n if (this._options.windowType === 'sliding') {\n // For sliding window, we can execute if we have capacity in the current window\n if (this._executionTimes.length < this.getLimit()) {\n this.execute(...args)\n return true\n }\n } else {\n // For fixed window, we need to check if we're in a new window\n const now = Date.now()\n const oldestExecution = Math.min(...this._executionTimes)\n const isNewWindow = oldestExecution + this.getWindow() <= now\n\n if (isNewWindow || this._executionTimes.length < this.getLimit()) {\n this.execute(...args)\n return true\n }\n }\n\n this.rejectFunction()\n return false\n }\n\n private execute(...args: Parameters<TFn>): void {\n if (!this.getEnabled()) return\n const now = Date.now()\n this._executionCount++\n this._executionTimes.push(now)\n this.fn(...args) // execute the function\n this._options.onExecute?.(this)\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.getWindow()\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.getLimit() - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow(): number {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this.getWindow() - Date.now()\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 a 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 * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\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 with a sliding window\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\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 * 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 rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAuCA,MAAM,iBAAoD;AAAA,EACxD,SAAS;AAAA,EACT,OAAO;AAAA,EACP,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,QAAQ;AAAA,EACR,YAAY;AACd;AAiCO,MAAM,YAAqC;AAAA,EAMhD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAkB;AAC1B,SAAQ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import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\nexport interface RateLimiterState {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Array of timestamps when executions occurred for rate limiting calculations\n */\n executionTimes: Array<number>\n /**\n * Number of function executions that have been rejected due to rate limiting\n */\n rejectionCount: number\n}\n\nfunction getDefaultRateLimiterState(): RateLimiterState {\n return structuredClone({\n executionCount: 0,\n executionTimes: [],\n rejectionCount: 0,\n })\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)\n /**\n * Initial state for the rate limiter\n */\n initialState?: Partial<RateLimiterState>\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n limit: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n window: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Omit<\n Required<RateLimiterOptions<any>>,\n 'initialState' | 'onExecute' | 'onReject'\n> = {\n enabled: true,\n limit: 1,\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a 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 * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via `rateLimiter.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n readonly store: Store<Readonly<RateLimiterState>> =\n new Store<RateLimiterState>(getDefaultRateLimiterState())\n options: RateLimiterOptions<TFn>\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n }\n\n /**\n * Updates the rate limiter options\n */\n setOptions = (newOptions: Partial<RateLimiterOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<RateLimiterState>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n return combinedState\n })\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n #getLimit = (): number => {\n return parseFunctionOrValue(this.options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n #getWindow = (): number => {\n return parseFunctionOrValue(this.options.window, this)\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 *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): boolean => {\n this.#cleanupOldExecutions()\n\n const relevantExecutionTimes = this.#getRelevantExecutionTimes()\n\n if (relevantExecutionTimes.length < this.#getLimit()) {\n this.#execute(...args)\n return true\n }\n\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(this)\n return false\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n const now = Date.now()\n this.fn(...args) // EXECUTE!\n this.store.state.executionTimes.push(now) // mutate state directly for performance\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n })\n this.options.onExecute?.(this)\n }\n\n #getRelevantExecutionTimes = (): Array<number> => {\n if (this.options.windowType === 'sliding') {\n // For sliding window, return all executions within the current window\n return this.store.state.executionTimes.filter(\n (time) => time > Date.now() - this.#getWindow(),\n )\n } else {\n // For fixed window, return all executions in the current window\n // The window starts from the oldest execution time\n const oldestExecution = Math.min(...this.store.state.executionTimes)\n const windowStart = oldestExecution\n return this.store.state.executionTimes.filter(\n (time) =>\n time >= windowStart && time <= windowStart + this.#getWindow(),\n )\n }\n }\n\n #cleanupOldExecutions = (): void => {\n const now = Date.now()\n const windowStart = now - this.#getWindow()\n this.#setState({\n executionTimes: this.store.state.executionTimes.filter(\n (time) => time > windowStart,\n ),\n })\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.#getRelevantExecutionTimes()\n return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow = (): number => {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = this.store.state.executionTimes[0] ?? Infinity\n return oldestExecution + this.#getWindow() - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset = (): void => {\n this.#setState(getDefaultRateLimiterState())\n }\n}\n\n/**\n * Creates a 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 * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via the underlying RateLimiter instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\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 with a sliding window\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\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 * 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 rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute\n}\n"],"names":["Store","parseFunctionOrValue"],"mappings":";;;;AAmBA,SAAS,6BAA+C;AACtD,SAAO,gBAAgB;AAAA,IACrB,gBAAgB;AAAA,IAChB,gBAAgB,CAAA;AAAA,IAChB,gBAAgB;AAAA,EAAA,CACjB;AACH;AA0CA,MAAM,iBAGF;AAAA,EACF,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,YAAY;AACd;AA8CO,MAAM,YAAqC;AAAA,EAKhD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AALV,SAAS,QACP,IAAIA,MAAAA,MAAwB,2BAAA,CAA4B;AAiB1D,SAAA,aAAa,CAAC,eAAuD;AACnE,WAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,WAAA;AAAA,IAAW;AAGlD,SAAA,YAAY,CAAC,aAA8C;AACzD,WAAK,MAAM,SAAS,CAAC,UAAU;AAC7B,cAAM,gBAAgB;AAAA,UACpB,GAAG;AAAA,UACH,GAAG;AAAA,QAAA;AAEL,eAAO;AAAA,MAAA,CACR;AAAA,IAAA;AAMH,SAAA,cAAc,MAAe;AAC3B,aAAO,CAAC,CAACC,MAAAA,qBAAqB,KAAK,QAAQ,SAAS,IAAI;AAAA,IAAA;AAM1D,SAAA,YAAY,MAAc;AACxB,aAAOA,MAAAA,qBAAqB,KAAK,QAAQ,OAAO,IAAI;AAAA,IAAA;AAMtD,SAAA,aAAa,MAAc;AACzB,a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;AAAA,UAC9C,CAAC,SAAS,OAAO;AAAA,QAAA;AAAA,MACnB,CACD;AAAA,IAAA;AAMH,SAAA,uBAAuB,MAAc;AACnC,YAAM,yBAAyB,KAAK,2BAAA;AACpC,aAAO,KAAK,IAAI,GAAG,KAAK,UAAA,IAAc,uBAAuB,MAAM;AAAA,IAAA;AAMrE,SAAA,uBAAuB,MAAc;AACnC,UAAI,KAAK,qBAAA,IAAyB,GAAG;AACnC,eAAO;AAAA,MAAA;AAET,YAAM,kBAAkB,KAAK,MAAM,MAAM,eAAe,CAAC,KAAK;AAC9D,aAAO,kBAAkB,KAAK,WAAA,IAAe,KAAK,IAAA;AAAA,IAAI;AAMxD,SAAA,QAAQ,MAAY;AAClB,WAAK,UAAU,4BAA4B;AAAA,IAAA;AA3I3C,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IAAA;AAEL,SAAK,UAAU,KAAK,QAAQ,gBAAgB,CAAA,CAAE;AAAA,EAAA;AAAA,EAUhD;AAAA,EAaA;AAAA,EAOA;AAAA,EAOA;AAAA,EAoCA;AAAA,EAWA;AAAA,EAkBA;AAmCF;AAgDO,SAAS,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AACtD,SAAO,YAAY;AACrB;;;"}
|
|
@@ -1,4 +1,19 @@
|
|
|
1
|
+
import { Store } from '@tanstack/store';
|
|
1
2
|
import { AnyFunction } from './types.cjs';
|
|
3
|
+
export interface RateLimiterState {
|
|
4
|
+
/**
|
|
5
|
+
* Number of function executions that have been completed
|
|
6
|
+
*/
|
|
7
|
+
executionCount: number;
|
|
8
|
+
/**
|
|
9
|
+
* Array of timestamps when executions occurred for rate limiting calculations
|
|
10
|
+
*/
|
|
11
|
+
executionTimes: Array<number>;
|
|
12
|
+
/**
|
|
13
|
+
* Number of function executions that have been rejected due to rate limiting
|
|
14
|
+
*/
|
|
15
|
+
rejectionCount: number;
|
|
16
|
+
}
|
|
2
17
|
/**
|
|
3
18
|
* Options for configuring a rate-limited function
|
|
4
19
|
*/
|
|
@@ -8,6 +23,10 @@ export interface RateLimiterOptions<TFn extends AnyFunction> {
|
|
|
8
23
|
* Defaults to true.
|
|
9
24
|
*/
|
|
10
25
|
enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean);
|
|
26
|
+
/**
|
|
27
|
+
* Initial state for the rate limiter
|
|
28
|
+
*/
|
|
29
|
+
initialState?: Partial<RateLimiterState>;
|
|
11
30
|
/**
|
|
12
31
|
* Maximum number of executions allowed within the time window.
|
|
13
32
|
* Can be a number or a callback function that receives the rate limiter instance and returns a number.
|
|
@@ -54,11 +73,24 @@ export interface RateLimiterOptions<TFn extends AnyFunction> {
|
|
|
54
73
|
* Rate limiting is best used for hard API limits or resource constraints. For UI updates or
|
|
55
74
|
* smoothing out frequent events, throttling or debouncing usually provide better user experience.
|
|
56
75
|
*
|
|
76
|
+
* State Management:
|
|
77
|
+
* - Uses TanStack Store for reactive state management
|
|
78
|
+
* - Use `initialState` to provide initial state values when creating the rate limiter
|
|
79
|
+
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
80
|
+
* - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
|
|
81
|
+
* - The state includes execution count, execution times, and rejection count
|
|
82
|
+
* - State can be accessed via `rateLimiter.store.state` when using the class directly
|
|
83
|
+
* - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`
|
|
84
|
+
*
|
|
57
85
|
* @example
|
|
58
86
|
* ```ts
|
|
59
87
|
* const rateLimiter = new RateLimiter(
|
|
60
88
|
* (id: string) => api.getData(id),
|
|
61
|
-
* {
|
|
89
|
+
* {
|
|
90
|
+
* limit: 5,
|
|
91
|
+
* window: 1000,
|
|
92
|
+
* windowType: 'sliding',
|
|
93
|
+
* }
|
|
62
94
|
* );
|
|
63
95
|
*
|
|
64
96
|
* // Will execute immediately until limit reached, then block
|
|
@@ -66,32 +98,15 @@ export interface RateLimiterOptions<TFn extends AnyFunction> {
|
|
|
66
98
|
* ```
|
|
67
99
|
*/
|
|
68
100
|
export declare class RateLimiter<TFn extends AnyFunction> {
|
|
101
|
+
#private;
|
|
69
102
|
private fn;
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
private _executionTimes;
|
|
73
|
-
private _options;
|
|
103
|
+
readonly store: Store<Readonly<RateLimiterState>>;
|
|
104
|
+
options: RateLimiterOptions<TFn>;
|
|
74
105
|
constructor(fn: TFn, initialOptions: RateLimiterOptions<TFn>);
|
|
75
106
|
/**
|
|
76
107
|
* Updates the rate limiter options
|
|
77
108
|
*/
|
|
78
|
-
setOptions(newOptions: Partial<RateLimiterOptions<TFn>>)
|
|
79
|
-
/**
|
|
80
|
-
* Returns the current rate limiter options
|
|
81
|
-
*/
|
|
82
|
-
getOptions(): Required<RateLimiterOptions<TFn>>;
|
|
83
|
-
/**
|
|
84
|
-
* Returns the current enabled state of the rate limiter
|
|
85
|
-
*/
|
|
86
|
-
getEnabled(): boolean;
|
|
87
|
-
/**
|
|
88
|
-
* Returns the current limit of executions allowed within the time window
|
|
89
|
-
*/
|
|
90
|
-
getLimit(): number;
|
|
91
|
-
/**
|
|
92
|
-
* Returns the current time window in milliseconds
|
|
93
|
-
*/
|
|
94
|
-
getWindow(): number;
|
|
109
|
+
setOptions: (newOptions: Partial<RateLimiterOptions<TFn>>) => void;
|
|
95
110
|
/**
|
|
96
111
|
* Attempts to execute the rate-limited function if within the configured limits.
|
|
97
112
|
* Will reject execution if the number of calls in the current window exceeds the limit.
|
|
@@ -107,30 +122,19 @@ export declare class RateLimiter<TFn extends AnyFunction> {
|
|
|
107
122
|
* rateLimiter.maybeExecute('arg1', 'arg2'); // false
|
|
108
123
|
* ```
|
|
109
124
|
*/
|
|
110
|
-
maybeExecute(...args: Parameters<TFn>)
|
|
111
|
-
private execute;
|
|
112
|
-
private rejectFunction;
|
|
113
|
-
private cleanupOldExecutions;
|
|
114
|
-
/**
|
|
115
|
-
* Returns the number of times the function has been executed
|
|
116
|
-
*/
|
|
117
|
-
getExecutionCount(): number;
|
|
118
|
-
/**
|
|
119
|
-
* Returns the number of times the function has been rejected
|
|
120
|
-
*/
|
|
121
|
-
getRejectionCount(): number;
|
|
125
|
+
maybeExecute: (...args: Parameters<TFn>) => boolean;
|
|
122
126
|
/**
|
|
123
127
|
* Returns the number of remaining executions allowed in the current window
|
|
124
128
|
*/
|
|
125
|
-
getRemainingInWindow()
|
|
129
|
+
getRemainingInWindow: () => number;
|
|
126
130
|
/**
|
|
127
131
|
* Returns the number of milliseconds until the next execution will be possible
|
|
128
132
|
*/
|
|
129
|
-
getMsUntilNextWindow()
|
|
133
|
+
getMsUntilNextWindow: () => number;
|
|
130
134
|
/**
|
|
131
135
|
* Resets the rate limiter state
|
|
132
136
|
*/
|
|
133
|
-
reset()
|
|
137
|
+
reset: () => void;
|
|
134
138
|
}
|
|
135
139
|
/**
|
|
136
140
|
* Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
|
|
@@ -146,6 +150,15 @@ export declare class RateLimiter<TFn extends AnyFunction> {
|
|
|
146
150
|
* - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
|
|
147
151
|
* consistent rate of execution over time.
|
|
148
152
|
*
|
|
153
|
+
* State Management:
|
|
154
|
+
* - Uses TanStack Store for reactive state management
|
|
155
|
+
* - Use `initialState` to provide initial state values when creating the rate limiter
|
|
156
|
+
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
157
|
+
* - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
|
|
158
|
+
* - The state includes execution count, execution times, and rejection count
|
|
159
|
+
* - State can be accessed via the underlying RateLimiter instance's `store.state` property
|
|
160
|
+
* - When using framework adapters (React/Solid), state is accessed from the hook's state property
|
|
161
|
+
*
|
|
149
162
|
* Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
|
|
150
163
|
* need to enforce a hard limit on the number of executions within a time period.
|
|
151
164
|
*
|
package/dist/cjs/throttler.cjs
CHANGED
|
@@ -1,145 +1,129 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const store = require("@tanstack/store");
|
|
3
4
|
const utils = require("./utils.cjs");
|
|
5
|
+
function getDefaultThrottlerState() {
|
|
6
|
+
return structuredClone({
|
|
7
|
+
executionCount: 0,
|
|
8
|
+
isPending: false,
|
|
9
|
+
lastArgs: void 0,
|
|
10
|
+
lastExecutionTime: 0,
|
|
11
|
+
nextExecutionTime: 0,
|
|
12
|
+
status: "idle"
|
|
13
|
+
});
|
|
14
|
+
}
|
|
4
15
|
const defaultOptions = {
|
|
5
16
|
enabled: true,
|
|
6
17
|
leading: true,
|
|
7
|
-
onExecute: () => {
|
|
8
|
-
},
|
|
9
18
|
trailing: true,
|
|
10
19
|
wait: 0
|
|
11
20
|
};
|
|
12
21
|
class Throttler {
|
|
13
22
|
constructor(fn, initialOptions) {
|
|
14
23
|
this.fn = fn;
|
|
15
|
-
this.
|
|
16
|
-
|
|
17
|
-
|
|
24
|
+
this.store = new store.Store(
|
|
25
|
+
getDefaultThrottlerState()
|
|
26
|
+
);
|
|
27
|
+
this.setOptions = (newOptions) => {
|
|
28
|
+
this.options = { ...this.options, ...newOptions };
|
|
29
|
+
if (!this.#getEnabled()) {
|
|
30
|
+
this.cancel();
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
this.#setState = (newState) => {
|
|
34
|
+
this.store.setState((state) => {
|
|
35
|
+
const combinedState = {
|
|
36
|
+
...state,
|
|
37
|
+
...newState
|
|
38
|
+
};
|
|
39
|
+
const { isPending } = combinedState;
|
|
40
|
+
return {
|
|
41
|
+
...combinedState,
|
|
42
|
+
status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
|
|
43
|
+
};
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
this.#getEnabled = () => {
|
|
47
|
+
return !!utils.parseFunctionOrValue(this.options.enabled, this);
|
|
48
|
+
};
|
|
49
|
+
this.#getWait = () => {
|
|
50
|
+
return utils.parseFunctionOrValue(this.options.wait, this);
|
|
51
|
+
};
|
|
52
|
+
this.maybeExecute = (...args) => {
|
|
53
|
+
const now = Date.now();
|
|
54
|
+
const timeSinceLastExecution = now - this.store.state.lastExecutionTime;
|
|
55
|
+
const wait = this.#getWait();
|
|
56
|
+
if (this.options.leading && timeSinceLastExecution >= wait) {
|
|
57
|
+
this.#execute(...args);
|
|
58
|
+
} else {
|
|
59
|
+
this.#setState({
|
|
60
|
+
lastArgs: args
|
|
61
|
+
});
|
|
62
|
+
if (!this.#timeoutId && this.options.trailing) {
|
|
63
|
+
const _timeSinceLastExecution = this.store.state.lastExecutionTime ? now - this.store.state.lastExecutionTime : 0;
|
|
64
|
+
const timeoutDuration = wait - _timeSinceLastExecution;
|
|
65
|
+
this.#setState({ isPending: true });
|
|
66
|
+
this.#timeoutId = setTimeout(() => {
|
|
67
|
+
const { lastArgs } = this.store.state;
|
|
68
|
+
if (lastArgs !== void 0) {
|
|
69
|
+
this.#execute(...lastArgs);
|
|
70
|
+
}
|
|
71
|
+
}, timeoutDuration);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
this.#execute = (...args) => {
|
|
76
|
+
if (!this.#getEnabled()) return;
|
|
77
|
+
this.fn(...args);
|
|
78
|
+
const lastExecutionTime = Date.now();
|
|
79
|
+
const nextExecutionTime = lastExecutionTime + this.#getWait();
|
|
80
|
+
this.#clearTimeout();
|
|
81
|
+
this.#setState({
|
|
82
|
+
executionCount: this.store.state.executionCount + 1,
|
|
83
|
+
lastExecutionTime,
|
|
84
|
+
nextExecutionTime,
|
|
85
|
+
isPending: false,
|
|
86
|
+
lastArgs: void 0
|
|
87
|
+
});
|
|
88
|
+
this.options.onExecute?.(this);
|
|
89
|
+
};
|
|
90
|
+
this.flush = () => {
|
|
91
|
+
if (this.store.state.isPending && this.store.state.lastArgs) {
|
|
92
|
+
this.#execute(...this.store.state.lastArgs);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
this.#clearTimeout = () => {
|
|
96
|
+
if (this.#timeoutId) {
|
|
97
|
+
clearTimeout(this.#timeoutId);
|
|
98
|
+
this.#timeoutId = void 0;
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
this.cancel = () => {
|
|
102
|
+
this.#clearTimeout();
|
|
103
|
+
this.#setState({
|
|
104
|
+
lastArgs: void 0,
|
|
105
|
+
isPending: false
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
this.reset = () => {
|
|
109
|
+
this.#setState(getDefaultThrottlerState());
|
|
110
|
+
};
|
|
111
|
+
this.options = {
|
|
18
112
|
...defaultOptions,
|
|
19
113
|
...initialOptions
|
|
20
114
|
};
|
|
115
|
+
this.#setState(this.options.initialState ?? {});
|
|
21
116
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
this.cancel();
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Returns the current throttler options
|
|
33
|
-
*/
|
|
34
|
-
getOptions() {
|
|
35
|
-
return this._options;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Returns the current enabled state of the throttler
|
|
39
|
-
*/
|
|
40
|
-
getEnabled() {
|
|
41
|
-
return utils.parseFunctionOrValue(this._options.enabled, this);
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Returns the current wait time in milliseconds
|
|
45
|
-
*/
|
|
46
|
-
getWait() {
|
|
47
|
-
return utils.parseFunctionOrValue(this._options.wait, this);
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Attempts to execute the throttled function. The execution behavior depends on the throttler options:
|
|
51
|
-
*
|
|
52
|
-
* - If enough time has passed since the last execution (>= wait period):
|
|
53
|
-
* - With leading=true: Executes immediately
|
|
54
|
-
* - With leading=false: Waits for the next trailing execution
|
|
55
|
-
*
|
|
56
|
-
* - If within the wait period:
|
|
57
|
-
* - With trailing=true: Schedules execution for end of wait period
|
|
58
|
-
* - With trailing=false: Drops the execution
|
|
59
|
-
*
|
|
60
|
-
* @example
|
|
61
|
-
* ```ts
|
|
62
|
-
* const throttled = new Throttler(fn, { wait: 1000 });
|
|
63
|
-
*
|
|
64
|
-
* // First call executes immediately
|
|
65
|
-
* throttled.maybeExecute('a', 'b');
|
|
66
|
-
*
|
|
67
|
-
* // Call during wait period - gets throttled
|
|
68
|
-
* throttled.maybeExecute('c', 'd');
|
|
69
|
-
* ```
|
|
70
|
-
*/
|
|
71
|
-
maybeExecute(...args) {
|
|
72
|
-
const now = Date.now();
|
|
73
|
-
const timeSinceLastExecution = now - this._lastExecutionTime;
|
|
74
|
-
const wait = this.getWait();
|
|
75
|
-
if (this._options.leading && timeSinceLastExecution >= wait) {
|
|
76
|
-
this.execute(...args);
|
|
77
|
-
} else {
|
|
78
|
-
this._lastArgs = args;
|
|
79
|
-
if (!this._timeoutId && this._options.trailing) {
|
|
80
|
-
const _timeSinceLastExecution = this._lastExecutionTime ? now - this._lastExecutionTime : 0;
|
|
81
|
-
const timeoutDuration = wait - _timeSinceLastExecution;
|
|
82
|
-
this._timeoutId = setTimeout(() => {
|
|
83
|
-
if (this._lastArgs !== void 0) {
|
|
84
|
-
this.execute(...this._lastArgs);
|
|
85
|
-
}
|
|
86
|
-
}, timeoutDuration);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
execute(...args) {
|
|
91
|
-
if (!this.getEnabled()) return;
|
|
92
|
-
this.fn(...args);
|
|
93
|
-
this._executionCount++;
|
|
94
|
-
this._lastExecutionTime = Date.now();
|
|
95
|
-
this._timeoutId = void 0;
|
|
96
|
-
this._lastArgs = void 0;
|
|
97
|
-
this._options.onExecute(this);
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* Cancels any pending trailing execution and clears internal state.
|
|
101
|
-
*
|
|
102
|
-
* If a trailing execution is scheduled (due to throttling with trailing=true),
|
|
103
|
-
* this will prevent that execution from occurring. The internal timeout and
|
|
104
|
-
* stored arguments will be cleared.
|
|
105
|
-
*
|
|
106
|
-
* Has no effect if there is no pending execution.
|
|
107
|
-
*/
|
|
108
|
-
cancel() {
|
|
109
|
-
if (this._timeoutId) {
|
|
110
|
-
clearTimeout(this._timeoutId);
|
|
111
|
-
this._timeoutId = void 0;
|
|
112
|
-
this._lastArgs = void 0;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Returns the last execution time
|
|
117
|
-
*/
|
|
118
|
-
getLastExecutionTime() {
|
|
119
|
-
return this._lastExecutionTime;
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Returns the next execution time
|
|
123
|
-
*/
|
|
124
|
-
getNextExecutionTime() {
|
|
125
|
-
return this._lastExecutionTime + this.getWait();
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Returns the number of times the function has been executed
|
|
129
|
-
*/
|
|
130
|
-
getExecutionCount() {
|
|
131
|
-
return this._executionCount;
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* Returns `true` if there is a pending execution
|
|
135
|
-
*/
|
|
136
|
-
getIsPending() {
|
|
137
|
-
return this.getEnabled() && !!this._timeoutId;
|
|
138
|
-
}
|
|
117
|
+
#timeoutId;
|
|
118
|
+
#setState;
|
|
119
|
+
#getEnabled;
|
|
120
|
+
#getWait;
|
|
121
|
+
#execute;
|
|
122
|
+
#clearTimeout;
|
|
139
123
|
}
|
|
140
124
|
function throttle(fn, initialOptions) {
|
|
141
125
|
const throttler = new Throttler(fn, initialOptions);
|
|
142
|
-
return throttler.maybeExecute
|
|
126
|
+
return throttler.maybeExecute;
|
|
143
127
|
}
|
|
144
128
|
exports.Throttler = Throttler;
|
|
145
129
|
exports.throttle = throttle;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"throttler.cjs","sources":["../../src/throttler.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (throttler: Throttler<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\nconst defaultOptions: Required<ThrottlerOptions<any>> = {\n enabled: true,\n leading: true,\n onExecute: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<TFn extends AnyFunction> {\n private _executionCount = 0\n private _lastArgs: Parameters<TFn> | undefined\n private _lastExecutionTime = 0\n private _options: Required<ThrottlerOptions<TFn>>\n private _timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the throttler options\n */\n setOptions(newOptions: Partial<ThrottlerOptions<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 throttler options\n */\n getOptions(): Required<ThrottlerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Returns the current enabled state of the throttler\n */\n getEnabled(): boolean {\n return parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute(...args: Parameters<TFn>): void {\n const now = Date.now()\n const timeSinceLastExecution = now - this._lastExecutionTime\n const wait = this.getWait()\n\n // Handle leading execution\n if (this._options.leading && timeSinceLastExecution >= wait) {\n this.execute(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this._lastArgs = args\n\n // Set up trailing execution if not already scheduled\n if (!this._timeoutId && this._options.trailing) {\n const _timeSinceLastExecution = this._lastExecutionTime\n ? now - this._lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this._timeoutId = setTimeout(() => {\n if (this._lastArgs !== undefined) {\n this.execute(...this._lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n private execute(...args: Parameters<TFn>): void {\n if (!this.getEnabled()) return\n this.fn(...args) // EXECUTE!\n this._executionCount++\n this._lastExecutionTime = Date.now()\n this._timeoutId = undefined\n this._lastArgs = undefined\n this._options.onExecute(this)\n }\n\n /**\n * Cancels any pending trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = undefined\n this._lastArgs = undefined\n }\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._lastExecutionTime + this.getWait()\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 there is a pending execution\n */\n getIsPending(): boolean {\n return this.getEnabled() && !!this._timeoutId\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * @example\n * ```ts\n * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute.bind(throttler)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAmCA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;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A,QAAQ,GAAG,KAAK,SAAS;AAAA,UAAA;AAAA,WAE/B,eAAe;AAAA,MAAA;AAAA,IACpB;AAAA,EACF;AAAA,EAGM,WAAW,MAA6B;AAC1C,QAAA,CAAC,KAAK,aAAc;AACnB,SAAA,GAAG,GAAG,IAAI;AACV,SAAA;AACA,SAAA,qBAAqB,KAAK,IAAI;AACnC,SAAK,aAAa;AAClB,SAAK,YAAY;AACZ,SAAA,SAAS,UAAU,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAY9B,SAAe;AACb,QAAI,KAAK,YAAY;AACnB,mBAAa,KAAK,UAAU;AAC5B,WAAK,aAAa;AAClB,WAAK,YAAY;AAAA,IAAA;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA,EAMF,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AACtB,WAAA,KAAK,qBAAqB,KAAK,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMhD,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACtB,WAAO,KAAK,WAAA,KAAgB,CAAC,CAAC,KAAK;AAAA,EAAA;AAEvC;AA4BgB,SAAA,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;;;"}
|
|
1
|
+
{"version":3,"file":"throttler.cjs","sources":["../../src/throttler.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\nexport interface ThrottlerState<TFn extends AnyFunction> {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Timestamp of the last function execution in milliseconds\n */\n lastExecutionTime: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number\n /**\n * Whether the throttler is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultThrottlerState<\n TFn extends AnyFunction,\n>(): ThrottlerState<TFn> {\n return structuredClone({\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n nextExecutionTime: 0,\n status: 'idle',\n })\n}\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Initial state for the throttler\n */\n initialState?: Partial<ThrottlerState<TFn>>\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (throttler: Throttler<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute'\n> = {\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via `throttler.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `throttler.state`\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<TFn extends AnyFunction> {\n readonly store: Store<Readonly<ThrottlerState<TFn>>> = new Store(\n getDefaultThrottlerState(),\n )\n options: ThrottlerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n }\n\n /**\n * Updates the throttler options\n */\n setOptions = (newOptions: Partial<ThrottlerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the throttler is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<ThrottlerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\n }\n\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n const now = Date.now()\n const timeSinceLastExecution = now - this.store.state.lastExecutionTime\n const wait = this.#getWait()\n\n // Handle leading execution\n if (this.options.leading && timeSinceLastExecution >= wait) {\n this.#execute(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this.#setState({\n lastArgs: args,\n })\n // Set up trailing execution if not already scheduled\n if (!this.#timeoutId && this.options.trailing) {\n // prevent large number if lastExecutionTime is undefined\n const _timeSinceLastExecution = this.store.state.lastExecutionTime\n ? now - this.store.state.lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this.#setState({ isPending: true })\n this.#timeoutId = setTimeout(() => {\n const { lastArgs } = this.store.state\n if (lastArgs !== undefined) {\n this.#execute(...lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n this.fn(...args) // EXECUTE!\n const lastExecutionTime = Date.now()\n const nextExecutionTime = lastExecutionTime + this.#getWait()\n this.#clearTimeout()\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n lastExecutionTime,\n nextExecutionTime,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(this)\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#execute(...this.store.state.lastArgs)\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n lastArgs: undefined,\n isPending: false,\n })\n }\n\n /**\n * Resets the throttler state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultThrottlerState<TFn>())\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via the underlying Throttler instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute\n}\n"],"names":["Store","parseFunctionOrValue"],"mappings":";;;;AA+BA,SAAS,2BAEgB;AACvB,SAAO,gBAAgB;AAAA,IACrB,gBAAgB;AAAA,IAChB,WAAW;AAAA,IACX,UAAU;AAAA,IACV,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,IACnB,QAAQ;AAAA,EAAA,CACT;AACH;AAsCA,MAAM,iBAGF;AAAA,EACF,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AAqCO,MAAM,UAAmC;AAAA,EAO9C,YACU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A8BF;AAoCO,SAAS,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAClD,SAAO,UAAU;AACnB;;;"}
|
package/dist/cjs/throttler.d.cts
CHANGED
|
@@ -1,4 +1,31 @@
|
|
|
1
|
+
import { Store } from '@tanstack/store';
|
|
1
2
|
import { AnyFunction } from './types.cjs';
|
|
3
|
+
export interface ThrottlerState<TFn extends AnyFunction> {
|
|
4
|
+
/**
|
|
5
|
+
* Number of function executions that have been completed
|
|
6
|
+
*/
|
|
7
|
+
executionCount: number;
|
|
8
|
+
/**
|
|
9
|
+
* The arguments from the most recent call to maybeExecute
|
|
10
|
+
*/
|
|
11
|
+
lastArgs: Parameters<TFn> | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* Timestamp of the last function execution in milliseconds
|
|
14
|
+
*/
|
|
15
|
+
lastExecutionTime: number;
|
|
16
|
+
/**
|
|
17
|
+
* Timestamp when the next execution can occur in milliseconds
|
|
18
|
+
*/
|
|
19
|
+
nextExecutionTime: number;
|
|
20
|
+
/**
|
|
21
|
+
* Whether the throttler is waiting for the timeout to trigger execution
|
|
22
|
+
*/
|
|
23
|
+
isPending: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Current execution status - 'idle' when not active, 'pending' when waiting for timeout
|
|
26
|
+
*/
|
|
27
|
+
status: 'disabled' | 'idle' | 'pending';
|
|
28
|
+
}
|
|
2
29
|
/**
|
|
3
30
|
* Options for configuring a throttled function
|
|
4
31
|
*/
|
|
@@ -9,6 +36,10 @@ export interface ThrottlerOptions<TFn extends AnyFunction> {
|
|
|
9
36
|
* Defaults to true.
|
|
10
37
|
*/
|
|
11
38
|
enabled?: boolean | ((throttler: Throttler<TFn>) => boolean);
|
|
39
|
+
/**
|
|
40
|
+
* Initial state for the throttler
|
|
41
|
+
*/
|
|
42
|
+
initialState?: Partial<ThrottlerState<TFn>>;
|
|
12
43
|
/**
|
|
13
44
|
* Whether to execute on the leading edge of the timeout.
|
|
14
45
|
* Defaults to true.
|
|
@@ -43,6 +74,14 @@ export interface ThrottlerOptions<TFn extends AnyFunction> {
|
|
|
43
74
|
*
|
|
44
75
|
* For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
|
|
45
76
|
*
|
|
77
|
+
* State Management:
|
|
78
|
+
* - Uses TanStack Store for reactive state management
|
|
79
|
+
* - Use `initialState` to provide initial state values when creating the throttler
|
|
80
|
+
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
81
|
+
* - The state includes execution count, last execution time, pending status, and more
|
|
82
|
+
* - State can be accessed via `throttler.store.state` when using the class directly
|
|
83
|
+
* - When using framework adapters (React/Solid), state is accessed from `throttler.state`
|
|
84
|
+
*
|
|
46
85
|
* @example
|
|
47
86
|
* ```ts
|
|
48
87
|
* const throttler = new Throttler(
|
|
@@ -58,29 +97,15 @@ export interface ThrottlerOptions<TFn extends AnyFunction> {
|
|
|
58
97
|
* ```
|
|
59
98
|
*/
|
|
60
99
|
export declare class Throttler<TFn extends AnyFunction> {
|
|
100
|
+
#private;
|
|
61
101
|
private fn;
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
private _lastExecutionTime;
|
|
65
|
-
private _options;
|
|
66
|
-
private _timeoutId;
|
|
102
|
+
readonly store: Store<Readonly<ThrottlerState<TFn>>>;
|
|
103
|
+
options: ThrottlerOptions<TFn>;
|
|
67
104
|
constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn>);
|
|
68
105
|
/**
|
|
69
106
|
* Updates the throttler options
|
|
70
107
|
*/
|
|
71
|
-
setOptions(newOptions: Partial<ThrottlerOptions<TFn>>)
|
|
72
|
-
/**
|
|
73
|
-
* Returns the current throttler options
|
|
74
|
-
*/
|
|
75
|
-
getOptions(): Required<ThrottlerOptions<TFn>>;
|
|
76
|
-
/**
|
|
77
|
-
* Returns the current enabled state of the throttler
|
|
78
|
-
*/
|
|
79
|
-
getEnabled(): boolean;
|
|
80
|
-
/**
|
|
81
|
-
* Returns the current wait time in milliseconds
|
|
82
|
-
*/
|
|
83
|
-
getWait(): number;
|
|
108
|
+
setOptions: (newOptions: Partial<ThrottlerOptions<TFn>>) => void;
|
|
84
109
|
/**
|
|
85
110
|
* Attempts to execute the throttled function. The execution behavior depends on the throttler options:
|
|
86
111
|
*
|
|
@@ -103,8 +128,11 @@ export declare class Throttler<TFn extends AnyFunction> {
|
|
|
103
128
|
* throttled.maybeExecute('c', 'd');
|
|
104
129
|
* ```
|
|
105
130
|
*/
|
|
106
|
-
maybeExecute(...args: Parameters<TFn>)
|
|
107
|
-
|
|
131
|
+
maybeExecute: (...args: Parameters<TFn>) => void;
|
|
132
|
+
/**
|
|
133
|
+
* Processes the current pending execution immediately
|
|
134
|
+
*/
|
|
135
|
+
flush: () => void;
|
|
108
136
|
/**
|
|
109
137
|
* Cancels any pending trailing execution and clears internal state.
|
|
110
138
|
*
|
|
@@ -114,23 +142,11 @@ export declare class Throttler<TFn extends AnyFunction> {
|
|
|
114
142
|
*
|
|
115
143
|
* Has no effect if there is no pending execution.
|
|
116
144
|
*/
|
|
117
|
-
cancel()
|
|
145
|
+
cancel: () => void;
|
|
118
146
|
/**
|
|
119
|
-
*
|
|
147
|
+
* Resets the throttler state to its default values
|
|
120
148
|
*/
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Returns the next execution time
|
|
124
|
-
*/
|
|
125
|
-
getNextExecutionTime(): number;
|
|
126
|
-
/**
|
|
127
|
-
* Returns the number of times the function has been executed
|
|
128
|
-
*/
|
|
129
|
-
getExecutionCount(): number;
|
|
130
|
-
/**
|
|
131
|
-
* Returns `true` if there is a pending execution
|
|
132
|
-
*/
|
|
133
|
-
getIsPending(): boolean;
|
|
149
|
+
reset: () => void;
|
|
134
150
|
}
|
|
135
151
|
/**
|
|
136
152
|
* Creates a throttled function that limits how often the provided function can execute.
|
|
@@ -145,6 +161,14 @@ export declare class Throttler<TFn extends AnyFunction> {
|
|
|
145
161
|
* For handling bursts of events, consider using debounce() instead. For hard execution
|
|
146
162
|
* limits, consider using rateLimit().
|
|
147
163
|
*
|
|
164
|
+
* State Management:
|
|
165
|
+
* - Uses TanStack Store for reactive state management
|
|
166
|
+
* - Use `initialState` to provide initial state values when creating the throttler
|
|
167
|
+
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
168
|
+
* - The state includes execution count, last execution time, pending status, and more
|
|
169
|
+
* - State can be accessed via the underlying Throttler instance's `store.state` property
|
|
170
|
+
* - When using framework adapters (React/Solid), state is accessed from the hook's state property
|
|
171
|
+
*
|
|
148
172
|
* @example
|
|
149
173
|
* ```ts
|
|
150
174
|
* // Basic throttling - max once per second
|