@tanstack/pacer 0.10.0 → 0.12.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.
Files changed (51) hide show
  1. package/dist/cjs/async-batcher.cjs.map +1 -1
  2. package/dist/cjs/async-batcher.d.cts +4 -4
  3. package/dist/cjs/async-debouncer.cjs +8 -13
  4. package/dist/cjs/async-debouncer.cjs.map +1 -1
  5. package/dist/cjs/async-debouncer.d.cts +1 -1
  6. package/dist/cjs/async-queuer.cjs +1 -1
  7. package/dist/cjs/async-queuer.cjs.map +1 -1
  8. package/dist/cjs/async-queuer.d.cts +3 -3
  9. package/dist/cjs/async-rate-limiter.cjs +2 -2
  10. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  11. package/dist/cjs/async-rate-limiter.d.cts +2 -2
  12. package/dist/cjs/async-throttler.cjs +14 -15
  13. package/dist/cjs/async-throttler.cjs.map +1 -1
  14. package/dist/cjs/async-throttler.d.cts +2 -2
  15. package/dist/cjs/debouncer.cjs +2 -1
  16. package/dist/cjs/debouncer.cjs.map +1 -1
  17. package/dist/cjs/queuer.cjs.map +1 -1
  18. package/dist/cjs/queuer.d.cts +1 -1
  19. package/dist/cjs/throttler.cjs +5 -0
  20. package/dist/cjs/throttler.cjs.map +1 -1
  21. package/dist/cjs/throttler.d.cts +1 -1
  22. package/dist/esm/async-batcher.d.ts +4 -4
  23. package/dist/esm/async-batcher.js.map +1 -1
  24. package/dist/esm/async-debouncer.d.ts +1 -1
  25. package/dist/esm/async-debouncer.js +8 -13
  26. package/dist/esm/async-debouncer.js.map +1 -1
  27. package/dist/esm/async-queuer.d.ts +3 -3
  28. package/dist/esm/async-queuer.js +1 -1
  29. package/dist/esm/async-queuer.js.map +1 -1
  30. package/dist/esm/async-rate-limiter.d.ts +2 -2
  31. package/dist/esm/async-rate-limiter.js +2 -2
  32. package/dist/esm/async-rate-limiter.js.map +1 -1
  33. package/dist/esm/async-throttler.d.ts +2 -2
  34. package/dist/esm/async-throttler.js +14 -15
  35. package/dist/esm/async-throttler.js.map +1 -1
  36. package/dist/esm/debouncer.js +2 -1
  37. package/dist/esm/debouncer.js.map +1 -1
  38. package/dist/esm/queuer.d.ts +1 -1
  39. package/dist/esm/queuer.js.map +1 -1
  40. package/dist/esm/throttler.d.ts +1 -1
  41. package/dist/esm/throttler.js +5 -0
  42. package/dist/esm/throttler.js.map +1 -1
  43. package/package.json +1 -1
  44. package/src/async-batcher.ts +6 -6
  45. package/src/async-debouncer.ts +14 -13
  46. package/src/async-queuer.ts +5 -5
  47. package/src/async-rate-limiter.ts +8 -4
  48. package/src/async-throttler.ts +20 -16
  49. package/src/debouncer.ts +2 -1
  50. package/src/queuer.ts +1 -1
  51. package/src/throttler.ts +6 -1
@@ -1 +1 @@
1
- {"version":3,"file":"throttler.js","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 * 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 * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number\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":[],"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,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAS,QAA8C,IAAI;AAAA,MACzD,yBAAA;AAAA,IAAyB;AAmB3B,SAAA,aAAa,CAAC,eAAqD;AACjE,WAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,WAAA;AAGrC,UAAI,CAAC,KAAK,eAAe;AACvB,aAAK,OAAA;AAAA,MAAO;AAAA,IACd;AAGF,SAAA,YAAY,CAAC,aAAiD;AAC5D,WAAK,MAAM,SAAS,CAAC,UAAU;AAC7B,cAAM,gBAAgB;AAAA,UACpB,GAAG;AAAA,UACH,GAAG;AAAA,QAAA;AAEL,cAAM,EAAE,cAAc;AACtB,eAAO;AAAA,UACL,GAAG;AAAA,UACH,QAAQ,CAAC,KAAK,gBACV,aACA,YACE,Y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ACD,WAAK,QAAQ,YAAY,IAAI;AAAA,IAAA;AAM/B,SAAA,QAAQ,MAAY;AAClB,UAAI,KAAK,MAAM,MAAM,aAAa,KAAK,MAAM,MAAM,UAAU;AAC3D,aAAK,SAAS,GAAG,KAAK,MAAM,MAAM,QAAQ;AAAA,MAAA;AAAA,IAC5C;AAGF,SAAA,gBAAgB,MAAY;AAC1B,UAAI,KAAK,YAAY;AACnB,qBAAa,KAAK,UAAU;AAC5B,aAAK,aAAa;AAAA,MAAA;AAAA,IACpB;AAYF,SAAA,SAAS,MAAY;AACnB,WAAK,cAAA;AACL,WAAK,UAAU;AAAA,QACb,UAAU;AAAA,QACV,WAAW;AAAA,MAAA,CACZ;AAAA,IAAA;AAMH,SAAA,QAAQ,MAAY;AAClB,WAAK,UAAU,0BAA+B;AAAA,IAAA;AAvJ9C,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IAAA;AAEL,SAAK,UAAU,KAAK,QAAQ,gBAAgB,CAAA,CAAE;AAAA,EAAA;AAAA,EAVhD;AAAA,EAyBA;AAAA,EAkBA;AAAA,EAIA;AAAA,EAyDA;AAAA,EAyBA;AA8BF;AAoCO,SAAS,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAClD,SAAO,UAAU;AACnB;"}
1
+ {"version":3,"file":"throttler.js","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 * 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 * 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 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 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 * 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":[],"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,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAS,QAA8C,IAAI;AAAA,MACz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A;AAAA,EAkBA;AAAA,EAIA;AAAA,EAyDA;AAAA,EA8BA;AA8BF;AAoCO,SAAS,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAClD,SAAO,UAAU;AACnB;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/pacer",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "Utilities for debouncing, throttling, rate-limiting, queuing, and more.",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -98,12 +98,12 @@ export interface AsyncBatcherOptions<TValue> {
98
98
  maxSize?: number
99
99
  /**
100
100
  * Optional error handler for when the batch function throws.
101
- * If provided, the handler will be called with the error and batcher instance.
101
+ * If provided, the handler will be called with the error, the batch of items that failed, and batcher instance.
102
102
  * This can be used alongside throwOnError - the handler will be called before any error is thrown.
103
103
  */
104
104
  onError?: (
105
105
  error: unknown,
106
- failedItems: Array<TValue>,
106
+ batch: Array<TValue>,
107
107
  batcher: AsyncBatcher<TValue>,
108
108
  ) => void
109
109
  /**
@@ -180,7 +180,7 @@ const defaultOptions: AsyncBatcherOptionsWithOptionalCallbacks<any> = {
180
180
  * - Error handling for failed batch operations
181
181
  *
182
182
  * Error Handling:
183
- * - If an `onError` handler is provided, it will be called with the error and batcher instance
183
+ * - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher instance
184
184
  * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
185
185
  * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
186
186
  * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
@@ -308,7 +308,7 @@ export class AsyncBatcher<TValue> {
308
308
  * You can also call this method manually to process the current batch at any time.
309
309
  *
310
310
  * @returns A promise that resolves with the result of the batch function, or undefined if an error occurred and was handled by onError
311
- * @throws The error from the batch function if no onError handler is configured
311
+ * @throws The error from the batch function if no onError handler is configured or throwOnError is true
312
312
  */
313
313
  #execute = async (): Promise<any> => {
314
314
  if (this.store.state.items.length === 0) {
@@ -317,7 +317,7 @@ export class AsyncBatcher<TValue> {
317
317
 
318
318
  const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)
319
319
  this.clear() // Clear items before processing to prevent race conditions
320
- this.options.onItemsChange?.(this) // Call onItemsChange to notify listeners that the items have changed
320
+ this.options.onItemsChange?.(this)
321
321
 
322
322
  this.#setState({ isExecuting: true })
323
323
 
@@ -404,7 +404,7 @@ export class AsyncBatcher<TValue> {
404
404
  * - Has state tracking for when batches are executing
405
405
  *
406
406
  * Error Handling:
407
- * - If an `onError` handler is provided, it will be called with the error and batcher instance
407
+ * - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher instance
408
408
  * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
409
409
  * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
410
410
  * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
@@ -81,7 +81,11 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
81
81
  * If provided, the handler will be called with the error and debouncer instance.
82
82
  * This can be used alongside throwOnError - the handler will be called before any error is thrown.
83
83
  */
84
- onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void
84
+ onError?: (
85
+ error: unknown,
86
+ args: Parameters<TFn>,
87
+ debouncer: AsyncDebouncer<TFn>,
88
+ ) => void
85
89
  /**
86
90
  * Optional callback to call when the debounced function is executed
87
91
  */
@@ -176,7 +180,6 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
176
180
  #resolvePreviousPromise:
177
181
  | ((value?: ReturnType<TFn> | undefined) => void)
178
182
  | null = null
179
- #rejectPreviousPromise: ((reason?: unknown) => void) | null = null
180
183
 
181
184
  constructor(
182
185
  private fn: TFn,
@@ -273,11 +276,15 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
273
276
 
274
277
  return new Promise((resolve, reject) => {
275
278
  this.#resolvePreviousPromise = resolve
276
- this.#rejectPreviousPromise = reject
279
+ // this.#rejectPreviousPromise = reject
277
280
  this.#timeoutId = setTimeout(async () => {
278
281
  // Execute trailing if enabled
279
282
  if (this.options.trailing && this.store.state.lastArgs) {
280
- await this.#execute(...this.store.state.lastArgs)
283
+ try {
284
+ await this.#execute(...this.store.state.lastArgs)
285
+ } catch (error) {
286
+ reject(error)
287
+ }
281
288
  }
282
289
 
283
290
  // Reset state and resolve
@@ -305,14 +312,15 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
305
312
  this.#setState({
306
313
  errorCount: this.store.state.errorCount + 1,
307
314
  })
308
- this.options.onError?.(error, this)
315
+ this.options.onError?.(error, args, this)
309
316
  if (this.options.throwOnError) {
310
- this.#rejectPreviousPromiseInternal(error)
317
+ throw error
311
318
  }
312
319
  } finally {
313
320
  this.#setState({
314
321
  isExecuting: false,
315
322
  isPending: false,
323
+ lastArgs: undefined,
316
324
  settleCount: this.store.state.settleCount + 1,
317
325
  })
318
326
  this.#abortController = null
@@ -345,13 +353,6 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
345
353
  }
346
354
  }
347
355
 
348
- #rejectPreviousPromiseInternal = (error: unknown): void => {
349
- if (this.#rejectPreviousPromise) {
350
- this.#rejectPreviousPromise(error)
351
- this.#rejectPreviousPromise = null
352
- }
353
- }
354
-
355
356
  #clearTimeout = (): void => {
356
357
  if (this.#timeoutId) {
357
358
  clearTimeout(this.#timeoutId)
@@ -141,7 +141,7 @@ export interface AsyncQueuerOptions<TValue> {
141
141
  * If provided, the handler will be called with the error and queuer instance.
142
142
  * This can be used alongside throwOnError - the handler will be called before any error is thrown.
143
143
  */
144
- onError?: (error: unknown, queuer: AsyncQueuer<TValue>) => void
144
+ onError?: (error: unknown, item: TValue, queuer: AsyncQueuer<TValue>) => void
145
145
  /**
146
146
  * Callback fired whenever an item expires in the queuer
147
147
  */
@@ -161,7 +161,7 @@ export interface AsyncQueuerOptions<TValue> {
161
161
  /**
162
162
  * Optional callback to call when a task succeeds
163
163
  */
164
- onSuccess?: (result: TValue, queuer: AsyncQueuer<TValue>) => void
164
+ onSuccess?: (result: any, queuer: AsyncQueuer<TValue>) => void
165
165
  /**
166
166
  * Whether the queuer should start processing tasks immediately or not.
167
167
  */
@@ -527,7 +527,7 @@ export class AsyncQueuer<TValue> {
527
527
  const item = this.getNextItem(position)
528
528
  if (item !== undefined) {
529
529
  try {
530
- const lastResult = await this.fn(item)
530
+ const lastResult = await this.fn(item) // EXECUTE!
531
531
  this.#setState({
532
532
  successCount: this.store.state.successCount + 1,
533
533
  lastResult,
@@ -537,7 +537,7 @@ export class AsyncQueuer<TValue> {
537
537
  this.#setState({
538
538
  errorCount: this.store.state.errorCount + 1,
539
539
  })
540
- this.options.onError?.(error, this)
540
+ this.options.onError?.(error, item, this)
541
541
  if (this.options.throwOnError) {
542
542
  throw error
543
543
  }
@@ -569,7 +569,7 @@ export class AsyncQueuer<TValue> {
569
569
  }
570
570
 
571
571
  /**
572
- * Processes all items in the queue as a batch using the provided function
572
+ * Processes all items in the queue as a batch using the provided function as an argument
573
573
  * The queue is cleared after processing
574
574
  */
575
575
  flushAsBatch = async (
@@ -81,11 +81,15 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
81
81
  * If provided, the handler will be called with the error and rate limiter instance.
82
82
  * This can be used alongside throwOnError - the handler will be called before any error is thrown.
83
83
  */
84
- onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void
84
+ onError?: (
85
+ error: unknown,
86
+ args: Parameters<TFn>,
87
+ rateLimiter: AsyncRateLimiter<TFn>,
88
+ ) => void
85
89
  /**
86
90
  * Optional callback function that is called when an execution is rejected due to rate limiting
87
91
  */
88
- onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void
92
+ onReject?: (args: Parameters<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void
89
93
  /**
90
94
  * Optional function to call when the rate-limited function is executed
91
95
  */
@@ -306,7 +310,7 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
306
310
  this.#setState({
307
311
  rejectionCount: this.store.state.rejectionCount + 1,
308
312
  })
309
- this.options.onReject?.(this)
313
+ this.options.onReject?.(args, this)
310
314
  return undefined
311
315
  }
312
316
 
@@ -334,7 +338,7 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
334
338
  this.#setState({
335
339
  errorCount: this.store.state.errorCount + 1,
336
340
  })
337
- this.options.onError?.(error, this)
341
+ this.options.onError?.(error, args, this)
338
342
  if (this.options.throwOnError) {
339
343
  throw error
340
344
  }
@@ -30,7 +30,7 @@ export interface AsyncThrottlerState<TFn extends AnyAsyncFunction> {
30
30
  /**
31
31
  * Timestamp when the next execution can occur in milliseconds
32
32
  */
33
- nextExecutionTime: number
33
+ nextExecutionTime: number | undefined
34
34
  /**
35
35
  * Number of function executions that have completed (either successfully or with errors)
36
36
  */
@@ -55,7 +55,7 @@ function getDefaultAsyncThrottlerState<
55
55
  lastArgs: undefined,
56
56
  lastExecutionTime: 0,
57
57
  lastResult: undefined,
58
- nextExecutionTime: 0,
58
+ nextExecutionTime: undefined,
59
59
  settleCount: 0,
60
60
  status: 'idle',
61
61
  successCount: 0,
@@ -86,7 +86,11 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
86
86
  * If provided, the handler will be called with the error and throttler instance.
87
87
  * This can be used alongside throwOnError - the handler will be called before any error is thrown.
88
88
  */
89
- onError?: (error: unknown, asyncThrottler: AsyncThrottler<TFn>) => void
89
+ onError?: (
90
+ error: unknown,
91
+ args: Parameters<TFn>,
92
+ asyncThrottler: AsyncThrottler<TFn>,
93
+ ) => void
90
94
  /**
91
95
  * Optional function to call when the throttled function is executed
92
96
  */
@@ -187,7 +191,6 @@ export class AsyncThrottler<TFn extends AnyAsyncFunction> {
187
191
  #resolvePreviousPromise:
188
192
  | ((value?: ReturnType<TFn> | undefined) => void)
189
193
  | null = null
190
- #rejectPreviousPromise: ((reason?: unknown) => void) | null = null
191
194
 
192
195
  constructor(
193
196
  private fn: TFn,
@@ -290,7 +293,6 @@ export class AsyncThrottler<TFn extends AnyAsyncFunction> {
290
293
  } else {
291
294
  return new Promise((resolve, reject) => {
292
295
  this.#resolvePreviousPromise = resolve
293
- this.#rejectPreviousPromise = reject
294
296
  // Clear any existing timeout to ensure we use the latest arguments
295
297
  this.#clearTimeout()
296
298
 
@@ -303,7 +305,11 @@ export class AsyncThrottler<TFn extends AnyAsyncFunction> {
303
305
  this.#setState({ isPending: true })
304
306
  this.#timeoutId = setTimeout(async () => {
305
307
  if (this.store.state.lastArgs !== undefined) {
306
- await this.#execute(...this.store.state.lastArgs)
308
+ try {
309
+ await this.#execute(...this.store.state.lastArgs) // EXECUTE!
310
+ } catch (error) {
311
+ reject(error)
312
+ }
307
313
  }
308
314
  this.#resolvePreviousPromise = null
309
315
  resolve(this.store.state.lastResult)
@@ -330,9 +336,9 @@ export class AsyncThrottler<TFn extends AnyAsyncFunction> {
330
336
  this.#setState({
331
337
  errorCount: this.store.state.errorCount + 1,
332
338
  })
333
- this.options.onError?.(error, this)
339
+ this.options.onError?.(error, args, this)
334
340
  if (this.options.throwOnError) {
335
- this.#rejectPreviousPromiseInternal(error)
341
+ throw error
336
342
  }
337
343
  } finally {
338
344
  const lastExecutionTime = Date.now()
@@ -346,6 +352,11 @@ export class AsyncThrottler<TFn extends AnyAsyncFunction> {
346
352
  })
347
353
  this.#abortController = null
348
354
  this.options.onSettled?.(this)
355
+ setTimeout(() => {
356
+ if (!this.store.state.isPending) {
357
+ this.#setState({ nextExecutionTime: undefined })
358
+ }
359
+ }, this.#getWait())
349
360
  }
350
361
  return this.store.state.lastResult
351
362
  }
@@ -374,13 +385,6 @@ export class AsyncThrottler<TFn extends AnyAsyncFunction> {
374
385
  }
375
386
  }
376
387
 
377
- #rejectPreviousPromiseInternal = (error: unknown): void => {
378
- if (this.#rejectPreviousPromise) {
379
- this.#rejectPreviousPromise(error)
380
- this.#rejectPreviousPromise = null
381
- }
382
- }
383
-
384
388
  #clearTimeout = (): void => {
385
389
  if (this.#timeoutId) {
386
390
  clearTimeout(this.#timeoutId)
@@ -391,7 +395,7 @@ export class AsyncThrottler<TFn extends AnyAsyncFunction> {
391
395
  #cancelPendingExecution = (): void => {
392
396
  this.#clearTimeout()
393
397
  if (this.#resolvePreviousPromise) {
394
- this.#resolvePreviousPromise(this.store.state.lastResult)
398
+ this.#resolvePreviousPromiseInternal()
395
399
  this.#resolvePreviousPromise = null
396
400
  }
397
401
  this.#setState({
package/src/debouncer.ts CHANGED
@@ -213,8 +213,9 @@ export class Debouncer<TFn extends AnyFunction> {
213
213
  if (!this.#getEnabled()) return undefined
214
214
  this.fn(...args) // EXECUTE!
215
215
  this.#setState({
216
- isPending: false,
217
216
  executionCount: this.store.state.executionCount + 1,
217
+ isPending: false,
218
+ lastArgs: undefined,
218
219
  })
219
220
  this.options.onExecute?.(this)
220
221
  }
package/src/queuer.ts CHANGED
@@ -516,7 +516,7 @@ export class Queuer<TValue> {
516
516
  }
517
517
 
518
518
  /**
519
- * Processes all items in the queue as a batch using the provided function
519
+ * Processes all items in the queue as a batch using the provided function as an argument
520
520
  * The queue is cleared after processing
521
521
  */
522
522
  flushAsBatch = (batchFunction: (items: Array<TValue>) => void): void => {
package/src/throttler.ts CHANGED
@@ -22,7 +22,7 @@ export interface ThrottlerState<TFn extends AnyFunction> {
22
22
  /**
23
23
  * Timestamp when the next execution can occur in milliseconds
24
24
  */
25
- nextExecutionTime: number
25
+ nextExecutionTime: number | undefined
26
26
  /**
27
27
  * Current execution status - 'idle' when not active, 'pending' when waiting for timeout
28
28
  */
@@ -246,6 +246,11 @@ export class Throttler<TFn extends AnyFunction> {
246
246
  lastArgs: undefined,
247
247
  })
248
248
  this.options.onExecute?.(this)
249
+ setTimeout(() => {
250
+ if (!this.store.state.isPending) {
251
+ this.#setState({ nextExecutionTime: undefined })
252
+ }
253
+ }, this.#getWait())
249
254
  }
250
255
 
251
256
  /**