@tanstack/pacer 0.17.0 → 0.17.2

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.
Files changed (60) hide show
  1. package/dist/async-batcher.cjs +6 -30
  2. package/dist/async-batcher.cjs.map +1 -1
  3. package/dist/async-batcher.d.cts +1 -1
  4. package/dist/async-batcher.d.ts +1 -1
  5. package/dist/async-batcher.js +4 -28
  6. package/dist/async-batcher.js.map +1 -1
  7. package/dist/async-debouncer.cjs +6 -26
  8. package/dist/async-debouncer.cjs.map +1 -1
  9. package/dist/async-debouncer.d.cts +1 -1
  10. package/dist/async-debouncer.d.ts +1 -1
  11. package/dist/async-debouncer.js +4 -24
  12. package/dist/async-debouncer.js.map +1 -1
  13. package/dist/async-queuer.cjs +7 -28
  14. package/dist/async-queuer.cjs.map +1 -1
  15. package/dist/async-queuer.d.cts +1 -1
  16. package/dist/async-queuer.d.ts +1 -1
  17. package/dist/async-queuer.js +5 -26
  18. package/dist/async-queuer.js.map +1 -1
  19. package/dist/async-rate-limiter.cjs +6 -26
  20. package/dist/async-rate-limiter.cjs.map +1 -1
  21. package/dist/async-rate-limiter.d.cts +1 -1
  22. package/dist/async-rate-limiter.d.ts +1 -1
  23. package/dist/async-rate-limiter.js +4 -24
  24. package/dist/async-rate-limiter.js.map +1 -1
  25. package/dist/async-retryer.cjs +5 -24
  26. package/dist/async-retryer.cjs.map +1 -1
  27. package/dist/async-retryer.d.cts +1 -1
  28. package/dist/async-retryer.d.ts +1 -1
  29. package/dist/async-retryer.js +3 -22
  30. package/dist/async-retryer.js.map +1 -1
  31. package/dist/async-throttler.cjs +6 -30
  32. package/dist/async-throttler.cjs.map +1 -1
  33. package/dist/async-throttler.d.cts +1 -1
  34. package/dist/async-throttler.d.ts +1 -1
  35. package/dist/async-throttler.js +4 -28
  36. package/dist/async-throttler.js.map +1 -1
  37. package/dist/batcher.cjs +2 -2
  38. package/dist/batcher.cjs.map +1 -1
  39. package/dist/batcher.js.map +1 -1
  40. package/dist/debouncer.cjs +2 -2
  41. package/dist/debouncer.cjs.map +1 -1
  42. package/dist/debouncer.js.map +1 -1
  43. package/dist/event-client.cjs +2 -2
  44. package/dist/event-client.cjs.map +1 -1
  45. package/dist/queuer.cjs +2 -2
  46. package/dist/queuer.cjs.map +1 -1
  47. package/dist/queuer.js.map +1 -1
  48. package/dist/rate-limiter.cjs +2 -2
  49. package/dist/rate-limiter.cjs.map +1 -1
  50. package/dist/rate-limiter.js.map +1 -1
  51. package/dist/throttler.cjs +2 -2
  52. package/dist/throttler.cjs.map +1 -1
  53. package/dist/throttler.js.map +1 -1
  54. package/package.json +1 -1
  55. package/src/async-batcher.ts +1 -1
  56. package/src/async-debouncer.ts +1 -1
  57. package/src/async-queuer.ts +2 -3
  58. package/src/async-rate-limiter.ts +1 -1
  59. package/src/async-retryer.ts +1 -1
  60. package/src/async-throttler.ts +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"throttler.js","names":["defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n>","fn: TFn","#getEnabled","#setState","#getWait","#execute","#timeoutId","#clearTimeout"],"sources":["../src/throttler.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\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 * Whether the throttler is waiting for the timeout to trigger execution\n */\n isPending: boolean\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 * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number | undefined\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 {\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n nextExecutionTime: 0,\n status: 'idle',\n maybeExecuteCount: 0,\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 * A key to identify the throttler.\n * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\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?: (args: Parameters<TFn>, 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\n/**\n * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.\n */\nexport function throttlerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<\n ThrottlerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\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 * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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 key: string | undefined\n options: ThrottlerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Throttler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as ThrottlerState<TFn>)\n this.setOptions(event.payload.options)\n })\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 // 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 emitChange('Throttler', this)\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 this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\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?.(args, this)\n setTimeout(() => {\n if (!this.store.state.isPending) {\n this.#setState({ nextExecutionTime: undefined })\n }\n }, this.#getWait())\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 * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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"],"mappings":";;;;;AAoCA,SAAS,2BAEgB;AACvB,QAAO;EACL,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,mBAAmB;EACnB,mBAAmB;EACnB,QAAQ;EACR,mBAAmB;EACpB;;;;;AA+CH,SAAgB,iBAKd,SAA6B;AAC7B,QAAO;;AAGT,MAAMA,iBAGF;CACF,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCD,IAAa,YAAb,MAAgD;CAM9C;CAEA,YACE,AAAOC,IACP,gBACA;EAFO;eAR8C,IAAI,MACzD,0BAA0B,CAC3B;qBA4Ba,eAAqD;AACjE,QAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;AAGjD,OAAI,CAAC,MAAKC,YAAa,CACrB,MAAK,QAAQ;;uBAqDD,GAAG,SAAgC;AACjD,SAAKC,SAAU,EACb,mBAAmB,KAAK,MAAM,MAAM,oBAAoB,GACzD,CAAC;GAEF,MAAM,MAAM,KAAK,KAAK;GACtB,MAAM,yBAAyB,MAAM,KAAK,MAAM,MAAM;GACtD,MAAM,OAAO,MAAKC,SAAU;AAG5B,OAAI,KAAK,QAAQ,WAAW,0BAA0B,KACpD,OAAKC,QAAS,GAAG,KAAK;QACjB;AAEL,UAAKF,SAAU,EACb,UAAU,MACX,CAAC;AAEF,QAAI,CAAC,MAAKG,aAAc,KAAK,QAAQ,UAAU;KAK7C,MAAM,kBAAkB,QAHQ,KAAK,MAAM,MAAM,oBAC7C,MAAM,KAAK,MAAM,MAAM,oBACvB;AAEJ,WAA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,oBAAoB,oBAAoB,MAAKE,SAAU;AAC7D,QAAKG,cAAe;AACpB,QAAKJ,SAAU;GACb,gBAAgB,KAAK,MAAM,MAAM,iBAAiB;GAClD;GACA;GACA,WAAW;GACX,UAAU;GACX,CAAC;AACF,OAAK,QAAQ,YAAY,MAAM,KAAK;AACpC,mBAAiB;AACf,OAAI,CAAC,KAAK,MAAM,MAAM,UACpB,OAAKA,SAAU,EAAE,mBAAmB,QAAW,CAAC;KAEjD,MAAKC,SAAU,CAAC;;CAYrB,sBAA4B;AAC1B,MAAI,MAAKE,WAAY;AACnB,gBAAa,MAAKA,UAAW;AAC7B,SAAKA,YAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiExB,SAAgB,SACd,IACA,gBACA;AAEA,QADkB,IAAI,UAAU,IAAI,eAAe,CAClC"}
1
+ {"version":3,"file":"throttler.js","names":["#getEnabled","#setState","#getWait","#execute","#timeoutId","#clearTimeout"],"sources":["../src/throttler.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\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 * Whether the throttler is waiting for the timeout to trigger execution\n */\n isPending: boolean\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 * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number | undefined\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 {\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n nextExecutionTime: 0,\n status: 'idle',\n maybeExecuteCount: 0,\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 * A key to identify the throttler.\n * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\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?: (args: Parameters<TFn>, 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\n/**\n * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.\n */\nexport function throttlerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<\n ThrottlerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\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 * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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 key: string | undefined\n options: ThrottlerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Throttler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as ThrottlerState<TFn>)\n this.setOptions(event.payload.options)\n })\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 // 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 emitChange('Throttler', this)\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 this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\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?.(args, this)\n setTimeout(() => {\n if (!this.store.state.isPending) {\n this.#setState({ nextExecutionTime: undefined })\n }\n }, this.#getWait())\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 * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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"],"mappings":";;;;;AAoCA,SAAS,2BAEgB;AACvB,QAAO;EACL,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,mBAAmB;EACnB,mBAAmB;EACnB,QAAQ;EACR,mBAAmB;EACpB;;;;;AA+CH,SAAgB,iBAKd,SAA6B;AAC7B,QAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCD,IAAa,YAAb,MAAgD;CAM9C;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eAR8C,IAAI,MACzD,0BAA0B,CAC3B;qBA4Ba,eAAqD;AACjE,QAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;AAGjD,OAAI,CAAC,MAAKA,YAAa,CACrB,MAAK,QAAQ;;uBAqDD,GAAG,SAAgC;AACjD,SAAKC,SAAU,EACb,mBAAmB,KAAK,MAAM,MAAM,oBAAoB,GACzD,CAAC;GAEF,MAAM,MAAM,KAAK,KAAK;GACtB,MAAM,yBAAyB,MAAM,KAAK,MAAM,MAAM;GACtD,MAAM,OAAO,MAAKC,SAAU;AAG5B,OAAI,KAAK,QAAQ,WAAW,0BAA0B,KACpD,OAAKC,QAAS,GAAG,KAAK;QACjB;AAEL,UAAKF,SAAU,EACb,UAAU,MACX,CAAC;AAEF,QAAI,CAAC,MAAKG,aAAc,KAAK,QAAQ,UAAU;KAK7C,MAAM,kBAAkB,QAHQ,KAAK,MAAM,MAAM,oBAC7C,MAAM,KAAK,MAAM,MAAM,oBACvB;AAEJ,WAAKH,SAAU,EAAE,WAAW,MAAM,CAAC;AACnC,WAAKG,YAAa,iBAAiB;MACjC,MAAM,EAAE,aAAa,KAAK,MAAM;AAChC,UAAI,aAAa,OACf,OAAKD,QA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AW;GACX,UAAU;GACX,CAAC;AACF,OAAK,QAAQ,YAAY,MAAM,KAAK;AACpC,mBAAiB;AACf,OAAI,CAAC,KAAK,MAAM,MAAM,UACpB,OAAKA,SAAU,EAAE,mBAAmB,QAAW,CAAC;KAEjD,MAAKC,SAAU,CAAC;;CAYrB,sBAA4B;AAC1B,MAAI,MAAKE,WAAY;AACnB,gBAAa,MAAKA,UAAW;AAC7B,SAAKA,YAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiExB,SAAgB,SACd,IACA,gBACA;AAEA,QADkB,IAAI,UAAU,IAAI,eAAe,CAClC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/pacer",
3
- "version": "0.17.0",
3
+ "version": "0.17.2",
4
4
  "description": "Utilities for debouncing, throttling, rate-limiting, queuing, and more.",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -476,7 +476,7 @@ export class AsyncBatcher<TValue> {
476
476
  * )
477
477
  * ```
478
478
  */
479
- getAbortSignal(executeCount?: number): AbortSignal | null {
479
+ getAbortSignal = (executeCount?: number): AbortSignal | null => {
480
480
  const count = executeCount ?? this.store.state.executeCount
481
481
  const retryer = this.asyncRetryers.get(count)
482
482
  return retryer?.getAbortSignal() ?? null
@@ -452,7 +452,7 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
452
452
  * )
453
453
  * ```
454
454
  */
455
- getAbortSignal(maybeExecuteCount?: number): AbortSignal | null {
455
+ getAbortSignal = (maybeExecuteCount?: number): AbortSignal | null => {
456
456
  const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount
457
457
  const retryer = this.asyncRetryers.get(count)
458
458
  return retryer?.getAbortSignal() ?? null
@@ -441,8 +441,7 @@ export class AsyncQueuer<TValue> {
441
441
  activeItems,
442
442
  })
443
443
  ;(async () => {
444
- const result = await this.execute()
445
- this.#setState({ lastResult: result })
444
+ await this.execute()
446
445
 
447
446
  const wait = this.#getWait()
448
447
  if (wait > 0) {
@@ -820,7 +819,7 @@ export class AsyncQueuer<TValue> {
820
819
  * )
821
820
  * ```
822
821
  */
823
- getAbortSignal(executeCount?: number): AbortSignal | null {
822
+ getAbortSignal = (executeCount?: number): AbortSignal | null => {
824
823
  const count = executeCount ?? this.store.state.executeCount
825
824
  const retryer = this.asyncRetryers.get(count)
826
825
  return retryer?.getAbortSignal() ?? null
@@ -522,7 +522,7 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
522
522
  * )
523
523
  * ```
524
524
  */
525
- getAbortSignal(maybeExecuteCount?: number): AbortSignal | null {
525
+ getAbortSignal = (maybeExecuteCount?: number): AbortSignal | null => {
526
526
  const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount
527
527
  const retryer = this.asyncRetryers.get(count)
528
528
  return retryer?.getAbortSignal() ?? null
@@ -594,7 +594,7 @@ export class AsyncRetryer<TFn extends AnyAsyncFunction> {
594
594
  * retryer.abort()
595
595
  * ```
596
596
  */
597
- getAbortSignal(): AbortSignal | null {
597
+ getAbortSignal = (): AbortSignal | null => {
598
598
  return this.#abortController?.signal ?? null
599
599
  }
600
600
 
@@ -516,7 +516,7 @@ export class AsyncThrottler<TFn extends AnyAsyncFunction> {
516
516
  * )
517
517
  * ```
518
518
  */
519
- getAbortSignal(maybeExecuteCount?: number): AbortSignal | null {
519
+ getAbortSignal = (maybeExecuteCount?: number): AbortSignal | null => {
520
520
  const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount
521
521
  const retryer = this.asyncRetryers.get(count)
522
522
  return retryer?.getAbortSignal() ?? null