@tanstack/pacer 0.20.0 → 0.21.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/async-batcher.cjs +72 -67
- package/dist/async-batcher.cjs.map +1 -1
- package/dist/async-batcher.js +72 -67
- package/dist/async-batcher.js.map +1 -1
- package/dist/async-debouncer.cjs +83 -74
- package/dist/async-debouncer.cjs.map +1 -1
- package/dist/async-debouncer.js +83 -74
- package/dist/async-debouncer.js.map +1 -1
- package/dist/async-queuer.cjs +102 -94
- package/dist/async-queuer.cjs.map +1 -1
- package/dist/async-queuer.js +102 -94
- package/dist/async-queuer.js.map +1 -1
- package/dist/async-rate-limiter.cjs +104 -93
- package/dist/async-rate-limiter.cjs.map +1 -1
- package/dist/async-rate-limiter.js +104 -93
- package/dist/async-rate-limiter.js.map +1 -1
- package/dist/async-retryer.cjs +67 -59
- package/dist/async-retryer.cjs.map +1 -1
- package/dist/async-retryer.js +67 -59
- package/dist/async-retryer.js.map +1 -1
- package/dist/async-throttler.cjs +81 -73
- package/dist/async-throttler.cjs.map +1 -1
- package/dist/async-throttler.js +81 -73
- package/dist/async-throttler.js.map +1 -1
- package/dist/batcher.cjs +45 -40
- package/dist/batcher.cjs.map +1 -1
- package/dist/batcher.js +45 -40
- package/dist/batcher.js.map +1 -1
- package/dist/debouncer.cjs +41 -36
- package/dist/debouncer.cjs.map +1 -1
- package/dist/debouncer.js +41 -36
- package/dist/debouncer.js.map +1 -1
- package/dist/queuer.cjs +92 -85
- package/dist/queuer.cjs.map +1 -1
- package/dist/queuer.js +92 -85
- package/dist/queuer.js.map +1 -1
- package/dist/rate-limiter.cjs +77 -66
- package/dist/rate-limiter.cjs.map +1 -1
- package/dist/rate-limiter.js +77 -66
- package/dist/rate-limiter.js.map +1 -1
- package/dist/throttler.cjs +49 -44
- package/dist/throttler.cjs.map +1 -1
- package/dist/throttler.js +49 -44
- package/dist/throttler.js.map +1 -1
- package/package.json +2 -2
- package/src/async-batcher.ts +1 -1
- package/src/async-debouncer.ts +1 -1
- package/src/async-queuer.ts +1 -1
- package/src/async-rate-limiter.ts +2 -2
- package/src/async-retryer.ts +1 -1
- package/src/async-throttler.ts +1 -1
- package/src/batcher.ts +1 -1
- package/src/debouncer.ts +1 -1
- package/src/queuer.ts +1 -1
- package/src/rate-limiter.ts +2 -2
- package/src/throttler.ts +1 -1
package/dist/batcher.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"batcher.js","names":["#setState","#execute","#clearTimeout","#timeoutId","#getWait"],"sources":["../src/batcher.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { OptionalKeys } from './types'\n\nexport interface BatcherState<TValue> {\n /**\n * Number of batch executions that have been completed\n */\n executionCount: number\n /**\n * Whether the batcher has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the batcher is waiting for the timeout to trigger batch processing\n */\n isPending: boolean\n /**\n * Array of items currently queued for batch processing\n */\n items: Array<TValue>\n /**\n * Number of items currently in the batch queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout\n */\n status: 'idle' | 'pending'\n /**\n * Total number of items that have been processed across all batches\n */\n totalItemsProcessed: number\n}\n\nfunction getDefaultBatcherState<TValue>(): BatcherState<TValue> {\n return {\n executionCount: 0,\n isEmpty: true,\n isPending: false,\n totalItemsProcessed: 0,\n items: [],\n size: 0,\n status: 'idle',\n }\n}\n\n/**\n * Options for configuring a Batcher instance\n */\nexport interface BatcherOptions<TValue> {\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean\n /**\n * Initial state for the batcher\n */\n initialState?: Partial<BatcherState<TValue>>\n /**\n * Optional key to identify this batcher instance.\n * If provided, the batcher will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Callback fired after a batch is processed\n */\n onExecute?: (batch: Array<TValue>, batcher: Batcher<TValue>) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: Batcher<TValue>) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\n */\n started?: boolean\n /**\n * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number | ((batcher: Batcher<TValue>) => number)\n}\n\ntype BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<BatcherOptions<TValue>>,\n 'initialState' | 'onExecute' | 'onItemsChange' | 'key'\n>\n\nconst defaultOptions: BatcherOptionsWithOptionalCallbacks<any> = {\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches.\n *\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncBatcher when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The Batcher provides a flexible way to implement batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the batcher\n * - Use `onExecute` callback to react to batch execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the batcher\n * - The state includes batch execution count, total items processed, items, and running status\n * - State can be accessed via `batcher.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `batcher.state`\n *\n * @example\n * ```ts\n * const batcher = new Batcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batch, batcher) => console.log('Batch executed:', batch)\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed\n * // batcher.flush() // manually trigger a batch\n * ```\n */\nexport class Batcher<TValue> {\n readonly store: Store<Readonly<BatcherState<TValue>>> = new Store(\n getDefaultBatcherState<TValue>(),\n )\n key: string | undefined\n options: BatcherOptionsWithOptionalCallbacks<TValue>\n #timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n public fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue>,\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-Batcher', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<BatcherState<TValue>>,\n )\n this.setOptions(\n event.payload.options as Partial<BatcherOptions<TValue>>,\n )\n })\n }\n }\n\n /**\n * Updates the batcher options\n */\n setOptions = (newOptions: Partial<BatcherOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<BatcherState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending, items } = combinedState\n const size = items.length\n const isEmpty = size === 0\n return {\n ...combinedState,\n isEmpty,\n size,\n status: isPending ? 'pending' : 'idle',\n }\n })\n emitChange('Batcher', this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Adds an item to the batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n */\n addItem = (item: TValue): void => {\n this.#setState({\n items: [...this.store.state.items, item],\n isPending: this.options.wait !== Infinity,\n })\n this.options.onItemsChange?.(this)\n\n const shouldProcess =\n this.store.state.items.length >= this.options.maxSize ||\n this.options.getShouldExecute(this.store.state.items, this)\n\n if (shouldProcess) {\n this.#execute()\n } else if (this.options.wait !== Infinity) {\n this.#clearTimeout() // clear any pending timeout to replace it with a new one\n this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait())\n }\n }\n\n /**\n * Processes the current batch of items.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches batchSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n */\n #execute = (): void => {\n if (this.store.state.items.length === 0) {\n return\n }\n\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this.clear() // Clear items before processing to prevent race conditions\n this.options.onItemsChange?.(this) // Call onItemsChange to notify listeners that the items have changed\n\n this.fn(batch) // EXECUTE\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n totalItemsProcessed: this.store.state.totalItemsProcessed + batch.length,\n })\n this.options.onExecute?.(batch, this)\n }\n\n /**\n * Processes the current batch of items immediately\n */\n flush = (): void => {\n this.#clearTimeout() // clear any pending timeout\n this.#execute() // execute immediately\n }\n\n /**\n * Returns a copy of all items in the batcher\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Removes all items from the batcher\n */\n clear = (): void => {\n this.#setState({ items: [], isPending: false })\n }\n\n /**\n * Cancels any pending execution that was scheduled.\n * Does NOT clear out the items.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({ isPending: false })\n }\n\n /**\n * Resets the batcher state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultBatcherState<TValue>())\n this.options.onItemsChange?.(this)\n }\n}\n\n/**\n * Creates a batcher that processes items in batches.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncBatch when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * @example\n * ```ts\n * const batchItems = batch<number>(\n * (items) => console.log('Processing:', items),\n * {\n * maxSize: 3,\n * onExecute: (batch, batcher) => console.log('Batch executed:', batch)\n * }\n * );\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function batch<TValue>(\n fn: (items: Array<TValue>) => void,\n options: BatcherOptions<TValue>,\n) {\n const batcher = new Batcher<TValue>(fn, options)\n return batcher.addItem\n}\n"],"mappings":";;;;;AAoCA,SAAS,yBAAuD;AAC9D,QAAO;EACL,gBAAgB;EAChB,SAAS;EACT,WAAW;EACX,qBAAqB;EACrB,OAAO,EAAE;EACT,MAAM;EACN,QAAQ;EACT;;AAqDH,MAAM,iBAA2D;CAC/D,wBAAwB;CACxB,SAAS;CACT,SAAS;CACT,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCD,IAAa,UAAb,MAA6B;CAM3B,aAAoC;CAEpC,YACE,AAAO,IACP,gBACA;EAFO;eAR+C,IAAI,MAC1D,wBAAgC,CACjC;qBAgCa,eAAsD;AAClE,QAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;;kBA8BxC,SAAuB;AAChC,SAAKA,SAAU;IACb,OAAO,CAAC,GAAG,KAAK,MAAM,MAAM,OAAO,KAAK;IACxC,WAAW,KAAK,QAAQ,SAAS;IAClC,CAAC;AACF,QAAK,QAAQ,gBAAgB,KAAK;AAMlC,OAHE,KAAK,MAAM,MAAM,MAAM,UAAU,KAAK,QAAQ,WAC9C,KAAK,QAAQ,iBAAiB,KAAK,MAAM,MAAM,OAAO,KAAK,CAG3D,OAAKC,SAAU;YACN,KAAK,QAAQ,SAAS,UAAU;AACzC,UAAKC,cAAe;AACpB,UAAKC,YAAa,iBAAiB,MAAKF,SAAU,EAAE,MAAKG,SAAU,CAAC;;;qBAiCpD;AAClB,SAAKF,cAAe;AACpB,SAAKD,SAAU;;4BAMmB;AAClC,UAAO,CAAC,GAAG,KAAK,MAAM,MAAM,MAAM;;qBAahB;AAClB,SAAKD,SAAU;IAAE,OAAO,EAAE;IAAE,WAAW;IAAO,CAAC;;sBAO5B;AACnB,SAAKE,cAAe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ACd,IACA,SACA;AAEA,QADgB,IAAI,QAAgB,IAAI,QAAQ,CACjC"}
|
|
1
|
+
{"version":3,"file":"batcher.js","names":["#setState","#execute","#clearTimeout","#timeoutId","#getWait"],"sources":["../src/batcher.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { OptionalKeys } from './types'\n\nexport interface BatcherState<TValue> {\n /**\n * Number of batch executions that have been completed\n */\n executionCount: number\n /**\n * Whether the batcher has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the batcher is waiting for the timeout to trigger batch processing\n */\n isPending: boolean\n /**\n * Array of items currently queued for batch processing\n */\n items: Array<TValue>\n /**\n * Number of items currently in the batch queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout\n */\n status: 'idle' | 'pending'\n /**\n * Total number of items that have been processed across all batches\n */\n totalItemsProcessed: number\n}\n\nfunction getDefaultBatcherState<TValue>(): BatcherState<TValue> {\n return {\n executionCount: 0,\n isEmpty: true,\n isPending: false,\n totalItemsProcessed: 0,\n items: [],\n size: 0,\n status: 'idle',\n }\n}\n\n/**\n * Options for configuring a Batcher instance\n */\nexport interface BatcherOptions<TValue> {\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean\n /**\n * Initial state for the batcher\n */\n initialState?: Partial<BatcherState<TValue>>\n /**\n * Optional key to identify this batcher instance.\n * If provided, the batcher will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Callback fired after a batch is processed\n */\n onExecute?: (batch: Array<TValue>, batcher: Batcher<TValue>) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: Batcher<TValue>) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\n */\n started?: boolean\n /**\n * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number | ((batcher: Batcher<TValue>) => number)\n}\n\ntype BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<BatcherOptions<TValue>>,\n 'initialState' | 'onExecute' | 'onItemsChange' | 'key'\n>\n\nconst defaultOptions: BatcherOptionsWithOptionalCallbacks<any> = {\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches.\n *\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncBatcher when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The Batcher provides a flexible way to implement batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the batcher\n * - Use `onExecute` callback to react to batch execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the batcher\n * - The state includes batch execution count, total items processed, items, and running status\n * - State can be accessed via `batcher.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `batcher.state`\n *\n * @example\n * ```ts\n * const batcher = new Batcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batch, batcher) => console.log('Batch executed:', batch)\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed\n * // batcher.flush() // manually trigger a batch\n * ```\n */\nexport class Batcher<TValue> {\n readonly store: Store<Readonly<BatcherState<TValue>>> = new Store(\n getDefaultBatcherState<TValue>(),\n )\n key: string | undefined\n options: BatcherOptionsWithOptionalCallbacks<TValue>\n #timeoutId: ReturnType<typeof setTimeout> | null = null\n\n constructor(\n public fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue>,\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-Batcher', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<BatcherState<TValue>>,\n )\n this.setOptions(\n event.payload.options as Partial<BatcherOptions<TValue>>,\n )\n })\n }\n }\n\n /**\n * Updates the batcher options\n */\n setOptions = (newOptions: Partial<BatcherOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<BatcherState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending, items } = combinedState\n const size = items.length\n const isEmpty = size === 0\n return {\n ...combinedState,\n isEmpty,\n size,\n status: isPending ? 'pending' : 'idle',\n }\n })\n emitChange('Batcher', this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Adds an item to the batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n */\n addItem = (item: TValue): void => {\n this.#setState({\n items: [...this.store.state.items, item],\n isPending: this.options.wait !== Infinity,\n })\n this.options.onItemsChange?.(this)\n\n const shouldProcess =\n this.store.state.items.length >= this.options.maxSize ||\n this.options.getShouldExecute(this.store.state.items, this)\n\n if (shouldProcess) {\n this.#execute()\n } else if (this.options.wait !== Infinity) {\n this.#clearTimeout() // clear any pending timeout to replace it with a new one\n this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait())\n }\n }\n\n /**\n * Processes the current batch of items.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches batchSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n */\n #execute = (): void => {\n if (this.store.state.items.length === 0) {\n return\n }\n\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this.clear() // Clear items before processing to prevent race conditions\n this.options.onItemsChange?.(this) // Call onItemsChange to notify listeners that the items have changed\n\n this.fn(batch) // EXECUTE\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n totalItemsProcessed: this.store.state.totalItemsProcessed + batch.length,\n })\n this.options.onExecute?.(batch, this)\n }\n\n /**\n * Processes the current batch of items immediately\n */\n flush = (): void => {\n this.#clearTimeout() // clear any pending timeout\n this.#execute() // execute immediately\n }\n\n /**\n * Returns a copy of all items in the batcher\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Removes all items from the batcher\n */\n clear = (): void => {\n this.#setState({ items: [], isPending: false })\n }\n\n /**\n * Cancels any pending execution that was scheduled.\n * Does NOT clear out the items.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({ isPending: false })\n }\n\n /**\n * Resets the batcher state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultBatcherState<TValue>())\n this.options.onItemsChange?.(this)\n }\n}\n\n/**\n * Creates a batcher that processes items in batches.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncBatch when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * @example\n * ```ts\n * const batchItems = batch<number>(\n * (items) => console.log('Processing:', items),\n * {\n * maxSize: 3,\n * onExecute: (batch, batcher) => console.log('Batch executed:', batch)\n * }\n * );\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function batch<TValue>(\n fn: (items: Array<TValue>) => void,\n options: BatcherOptions<TValue>,\n) {\n const batcher = new Batcher<TValue>(fn, options)\n return batcher.addItem\n}\n"],"mappings":";;;;;AAoCA,SAAS,yBAAuD;AAC9D,QAAO;EACL,gBAAgB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O;AACZ,QAAK,QAAQ,gBAAgB,KAAK;AAElC,QAAK,GAAG,MAAM;AACd,SAAKJ,SAAU;IACb,gBAAgB,KAAK,MAAM,MAAM,iBAAiB;IAClD,qBAAqB,KAAK,MAAM,MAAM,sBAAsB,MAAM;IACnE,CAAC;AACF,QAAK,QAAQ,YAAY,OAAO,KAAK;;qBAMnB;AAClB,SAAKE,cAAe;AACpB,SAAKD,SAAU;;4BAMmB;AAClC,UAAO,CAAC,GAAG,KAAK,MAAM,MAAM,MAAM;;6BAGR;AAC1B,OAAI,MAAKE,WAAY;AACnB,iBAAa,MAAKA,UAAW;AAC7B,UAAKA,YAAa;;;qBAOF;AAClB,SAAKH,SAAU;IAAE,OAAO,EAAE;IAAE,WAAW;IAAO,CAAC;;sBAO5B;AACnB,SAAKE,cAAe;AACpB,SAAKF,SAAU,EAAE,WAAW,OAAO,CAAC;;qBAMlB;AAClB,SAAKA,SAAU,wBAAgC,CAAC;AAChD,QAAK,QAAQ,gBAAgB,KAAK;;AA9IlC,OAAK,MAAM,eAAe;AAC1B,OAAK,UAAU;GACb,GAAG;GACH,GAAG;GACJ;AACD,QAAKA,SAAU,KAAK,QAAQ,gBAAgB,EAAE,CAAC;AAE/C,MAAI,KAAK,IACP,kBAAiB,GAAG,cAAc,UAAU;AAC1C,OAAI,MAAM,QAAQ,QAAQ,KAAK,IAAK;AACpC,SAAKA,SACH,MAAM,QAAQ,MAAM,MACrB;AACD,QAAK,WACH,MAAM,QAAQ,QACf;IACD;;CAWN;CAmBA;;;;;;;;;;CAoCA;CAgCA;;;;;;;;;;;;;;;;;;;;;;AAoDF,SAAgB,MACd,IACA,SACA;AAEA,QADgB,IAAI,QAAgB,IAAI,QAAQ,CACjC"}
|
package/dist/debouncer.cjs
CHANGED
|
@@ -70,6 +70,26 @@ var Debouncer = class {
|
|
|
70
70
|
};
|
|
71
71
|
if (!this.#getEnabled()) this.cancel();
|
|
72
72
|
};
|
|
73
|
+
this.#setState = (newState) => {
|
|
74
|
+
this.store.setState((state) => {
|
|
75
|
+
const combinedState = {
|
|
76
|
+
...state,
|
|
77
|
+
...newState
|
|
78
|
+
};
|
|
79
|
+
const { isPending } = combinedState;
|
|
80
|
+
return {
|
|
81
|
+
...combinedState,
|
|
82
|
+
status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
|
|
83
|
+
};
|
|
84
|
+
});
|
|
85
|
+
require_event_client.emitChange("Debouncer", this);
|
|
86
|
+
};
|
|
87
|
+
this.#getEnabled = () => {
|
|
88
|
+
return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
|
|
89
|
+
};
|
|
90
|
+
this.#getWait = () => {
|
|
91
|
+
return require_utils.parseFunctionOrValue(this.options.wait, this);
|
|
92
|
+
};
|
|
73
93
|
this.maybeExecute = (...args) => {
|
|
74
94
|
if (!this.#getEnabled()) return void 0;
|
|
75
95
|
this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
|
|
@@ -89,12 +109,28 @@ var Debouncer = class {
|
|
|
89
109
|
if (this.options.trailing && !_didLeadingExecute) this.#execute(...args);
|
|
90
110
|
}, this.#getWait());
|
|
91
111
|
};
|
|
112
|
+
this.#execute = (...args) => {
|
|
113
|
+
if (!this.#getEnabled()) return void 0;
|
|
114
|
+
this.fn(...args);
|
|
115
|
+
this.#setState({
|
|
116
|
+
executionCount: this.store.state.executionCount + 1,
|
|
117
|
+
isPending: false,
|
|
118
|
+
lastArgs: void 0
|
|
119
|
+
});
|
|
120
|
+
this.options.onExecute?.(args, this);
|
|
121
|
+
};
|
|
92
122
|
this.flush = () => {
|
|
93
123
|
if (this.store.state.isPending && this.store.state.lastArgs) {
|
|
94
124
|
this.#clearTimeout();
|
|
95
125
|
this.#execute(...this.store.state.lastArgs);
|
|
96
126
|
}
|
|
97
127
|
};
|
|
128
|
+
this.#clearTimeout = () => {
|
|
129
|
+
if (this.#timeoutId) {
|
|
130
|
+
clearTimeout(this.#timeoutId);
|
|
131
|
+
this.#timeoutId = void 0;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
98
134
|
this.cancel = () => {
|
|
99
135
|
this.#clearTimeout();
|
|
100
136
|
this.#setState({
|
|
@@ -117,48 +153,17 @@ var Debouncer = class {
|
|
|
117
153
|
this.setOptions(event.payload.options);
|
|
118
154
|
});
|
|
119
155
|
}
|
|
120
|
-
#setState
|
|
121
|
-
this.store.setState((state) => {
|
|
122
|
-
const combinedState = {
|
|
123
|
-
...state,
|
|
124
|
-
...newState
|
|
125
|
-
};
|
|
126
|
-
const { isPending } = combinedState;
|
|
127
|
-
return {
|
|
128
|
-
...combinedState,
|
|
129
|
-
status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
|
|
130
|
-
};
|
|
131
|
-
});
|
|
132
|
-
require_event_client.emitChange("Debouncer", this);
|
|
133
|
-
};
|
|
156
|
+
#setState;
|
|
134
157
|
/**
|
|
135
158
|
* Returns the current enabled state of the debouncer
|
|
136
159
|
*/
|
|
137
|
-
#getEnabled
|
|
138
|
-
return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
|
|
139
|
-
};
|
|
160
|
+
#getEnabled;
|
|
140
161
|
/**
|
|
141
162
|
* Returns the current wait time in milliseconds
|
|
142
163
|
*/
|
|
143
|
-
#getWait
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
#execute = (...args) => {
|
|
147
|
-
if (!this.#getEnabled()) return void 0;
|
|
148
|
-
this.fn(...args);
|
|
149
|
-
this.#setState({
|
|
150
|
-
executionCount: this.store.state.executionCount + 1,
|
|
151
|
-
isPending: false,
|
|
152
|
-
lastArgs: void 0
|
|
153
|
-
});
|
|
154
|
-
this.options.onExecute?.(args, this);
|
|
155
|
-
};
|
|
156
|
-
#clearTimeout = () => {
|
|
157
|
-
if (this.#timeoutId) {
|
|
158
|
-
clearTimeout(this.#timeoutId);
|
|
159
|
-
this.#timeoutId = void 0;
|
|
160
|
-
}
|
|
161
|
-
};
|
|
164
|
+
#getWait;
|
|
165
|
+
#execute;
|
|
166
|
+
#clearTimeout;
|
|
162
167
|
};
|
|
163
168
|
/**
|
|
164
169
|
* Creates a debounced function that delays invoking the provided function until after a specified wait time.
|
package/dist/debouncer.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debouncer.cjs","names":["Store","#getEnabled","#setState","#execute","#timeoutId","#getWait","#clearTimeout","parseFunctionOrValue"],"sources":["../src/debouncer.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 DebouncerState<TFn extends AnyFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the debouncer 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 * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultDebouncerState<\n TFn extends AnyFunction,\n>(): DebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Initial state for the debouncer\n */\n initialState?: Partial<DebouncerState<TFn>>\n /**\n * A key to identify the debouncer.\n * If provided, the debouncer 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 * The first call will execute immediately and the rest will wait the delay.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds before executing the function.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.\n */\nexport function debouncerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<DebouncerOptions<TFn>> = Partial<\n DebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a debounced function.\n *\n * Debouncing ensures that a function is only executed after a certain amount of time has passed\n * since its last invocation. This is useful for handling frequent events like window resizing,\n * scroll events, or input changes where you want to limit the rate of execution.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The debounced function can be configured to execute either at the start of the delay period\n * (leading edge) or at the end (trailing edge, default). Each new call during the wait period\n * will reset the timer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via `debouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\n *\n * // Will only save after 500ms of no new input\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class Debouncer<TFn extends AnyFunction> {\n readonly store: Store<Readonly<DebouncerState<TFn>>> = new Store(\n getDefaultDebouncerState<TFn>(),\n )\n key: string | undefined\n options: DebouncerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: DebouncerOptions<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-Debouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<DebouncerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<DebouncerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions = (newOptions: Partial<DebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<DebouncerState<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('Debouncer', this)\n }\n\n /**\n * Returns the current enabled state of the debouncer\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 debounced function\n * If a call is already in progress, it will be queued\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n _didLeadingExecute = true\n this.#execute(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (this.options.trailing) {\n this.#setState({ isPending: true, lastArgs: args })\n }\n\n // Clear any existing timeout\n if (this.#timeoutId) clearTimeout(this.#timeoutId)\n\n // Set new timeout that will reset canLeadingExecute and execute trailing only if enabled and did not execute leading\n this.#timeoutId = setTimeout(() => {\n this.#setState({ canLeadingExecute: true })\n if (this.options.trailing && !_didLeadingExecute) {\n this.#execute(...args)\n }\n }, this.#getWait())\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, 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.#clearTimeout() // clear any pending timeout\n this.#execute(...this.store.state.lastArgs) // execute immediately\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 execution\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n canLeadingExecute: true,\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultDebouncerState<TFn>())\n }\n}\n\n/**\n * Creates a debounced function that delays invoking the provided function until after a specified wait time.\n * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * If leading option is true, the function will execute immediately on the first call, then wait the delay\n * before allowing another execution.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via the underlying Debouncer 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 * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute\n}\n"],"mappings":";;;;;;AAgCA,SAAS,2BAEgB;AACvB,QAAO;EACL,mBAAmB;EACnB,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,QAAQ;EACR,mBAAmB;EACpB;;;;;AAgDH,SAAgB,iBAKd,SAA6B;AAC7B,QAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCD,IAAa,YAAb,MAAgD;CAM9C;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eAR8C,IAAIA,sBACzD,0BAA+B,CAChC;qBA8Ba,eAAqD;AACjE,QAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;AAGjD,OAAI,CAAC,MAAKC,YAAa,CACrB,MAAK,QAAQ;;uBAyCD,GAAG,SAAgC;AACjD,OAAI,CAAC,MAAKA,YAAa,CAAE,QAAO;AAEhC,SAAKC,SAAU,EACb,mBAAmB,KAAK,MAAM,MAAM,oBAAoB,GACzD,CAAC;GAEF,IAAI,qBAAqB;AAGzB,OAAI,KAAK,QAAQ,WAAW,KAAK,MAAM,MAAM,mBAAmB;AAC9D,UAAKA,SAAU,EAAE,mBAAmB,OAAO,CAAC;AAC5C,yBAAqB;AACrB,UAAKC,QAAS,GAAG,KAAK;;AAIxB,OAAI,KAAK,QAAQ,SACf,OAAKD,SAAU;IAAE,WAAW;IAAM,UAAU;IAAM,CAAC;AAIrD,OAAI,MAAKE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AAO;AAChC,OAAK,GAAG,GAAG,KAAK;AAChB,QAAKC,SAAU;GACb,gBAAgB,KAAK,MAAM,MAAM,iBAAiB;GAClD,WAAW;GACX,UAAU;GACX,CAAC;AACF,OAAK,QAAQ,YAAY,MAAM,KAAK;;CAatC,sBAA4B;AAC1B,MAAI,MAAKE,WAAY;AACnB,gBAAa,MAAKA,UAAW;AAC7B,SAAKA,YAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDxB,SAAgB,SACd,IACA,gBACoC;AAEpC,QADkB,IAAI,UAAU,IAAI,eAAe,CAClC"}
|
|
1
|
+
{"version":3,"file":"debouncer.cjs","names":["Store","#getEnabled","parseFunctionOrValue","#setState","#execute","#timeoutId","#getWait","#clearTimeout"],"sources":["../src/debouncer.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 DebouncerState<TFn extends AnyFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the debouncer 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 * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultDebouncerState<\n TFn extends AnyFunction,\n>(): DebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Initial state for the debouncer\n */\n initialState?: Partial<DebouncerState<TFn>>\n /**\n * A key to identify the debouncer.\n * If provided, the debouncer 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 * The first call will execute immediately and the rest will wait the delay.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds before executing the function.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.\n */\nexport function debouncerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<DebouncerOptions<TFn>> = Partial<\n DebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a debounced function.\n *\n * Debouncing ensures that a function is only executed after a certain amount of time has passed\n * since its last invocation. This is useful for handling frequent events like window resizing,\n * scroll events, or input changes where you want to limit the rate of execution.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The debounced function can be configured to execute either at the start of the delay period\n * (leading edge) or at the end (trailing edge, default). Each new call during the wait period\n * will reset the timer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via `debouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\n *\n * // Will only save after 500ms of no new input\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class Debouncer<TFn extends AnyFunction> {\n readonly store: Store<Readonly<DebouncerState<TFn>>> = new Store(\n getDefaultDebouncerState<TFn>(),\n )\n key: string | undefined\n options: DebouncerOptions<TFn>\n #timeoutId: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: DebouncerOptions<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-Debouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<DebouncerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<DebouncerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions = (newOptions: Partial<DebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<DebouncerState<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('Debouncer', this)\n }\n\n /**\n * Returns the current enabled state of the debouncer\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 debounced function\n * If a call is already in progress, it will be queued\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n _didLeadingExecute = true\n this.#execute(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (this.options.trailing) {\n this.#setState({ isPending: true, lastArgs: args })\n }\n\n // Clear any existing timeout\n if (this.#timeoutId) clearTimeout(this.#timeoutId)\n\n // Set new timeout that will reset canLeadingExecute and execute trailing only if enabled and did not execute leading\n this.#timeoutId = setTimeout(() => {\n this.#setState({ canLeadingExecute: true })\n if (this.options.trailing && !_didLeadingExecute) {\n this.#execute(...args)\n }\n }, this.#getWait())\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, 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.#clearTimeout() // clear any pending timeout\n this.#execute(...this.store.state.lastArgs) // execute immediately\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 execution\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n canLeadingExecute: true,\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultDebouncerState<TFn>())\n }\n}\n\n/**\n * Creates a debounced function that delays invoking the provided function until after a specified wait time.\n * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * If leading option is true, the function will execute immediately on the first call, then wait the delay\n * before allowing another execution.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via the underlying Debouncer 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 * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute\n}\n"],"mappings":";;;;;;AAgCA,SAAS,2BAEgB;AACvB,QAAO;EACL,mBAAmB;EACnB,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,QAAQ;EACR,mBAAmB;EACpB;;;;;AAgDH,SAAgB,iBAKd,SAA6B;AAC7B,QAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCD,IAAa,YAAb,MAAgD;CAM9C;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eAR8C,IAAIA,sBACzD,0BAA+B,CAChC;qBA8Ba,eAAqD;AACjE,QAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;AAGjD,OAAI,CAAC,MAAKC,YAAa,CACrB,MAAK,QAAQ;;oBAIJ,aAAiD;AAC5D,QAAK,MAAM,UAAU,UAAU;IAC7B,MAAM,gBAAgB;KACpB,GAAG;KACH,GAAG;KACJ;IACD,MAAM,EAAE,cAAc;AACtB,WAAO;KACL,GAAG;KACH,QAAQ,CAAC,MAAKA,YAAa,G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AAa;;;sBAOD;AACnB,SAAKE,cAAe;AACpB,SAAKJ,SAAU;IACb,mBAAmB;IACnB,WAAW;IACZ,CAAC;;qBAMgB;AAClB,SAAKA,SAAU,0BAA+B,CAAC;;AA/I/C,OAAK,MAAM,eAAe;AAC1B,OAAK,UAAU;GACb,GAAG;GACH,GAAG;GACJ;AACD,QAAKA,SAAU,KAAK,QAAQ,gBAAgB,EAAE,CAAC;AAE/C,MAAI,KAAK,IACP,uCAAiB,GAAG,gBAAgB,UAAU;AAC5C,OAAI,MAAM,QAAQ,QAAQ,KAAK,IAAK;AACpC,SAAKA,SACH,MAAM,QAAQ,MAAM,MACrB;AACD,QAAK,WAAW,MAAM,QAAQ,QAA0C;IACxE;;CAgBN;;;;CAsBA;;;;CAOA;CAyCA;CAqBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDF,SAAgB,SACd,IACA,gBACoC;AAEpC,QADkB,IAAI,UAAU,IAAI,eAAe,CAClC"}
|
package/dist/debouncer.js
CHANGED
|
@@ -69,6 +69,26 @@ var Debouncer = class {
|
|
|
69
69
|
};
|
|
70
70
|
if (!this.#getEnabled()) this.cancel();
|
|
71
71
|
};
|
|
72
|
+
this.#setState = (newState) => {
|
|
73
|
+
this.store.setState((state) => {
|
|
74
|
+
const combinedState = {
|
|
75
|
+
...state,
|
|
76
|
+
...newState
|
|
77
|
+
};
|
|
78
|
+
const { isPending } = combinedState;
|
|
79
|
+
return {
|
|
80
|
+
...combinedState,
|
|
81
|
+
status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
|
|
82
|
+
};
|
|
83
|
+
});
|
|
84
|
+
emitChange("Debouncer", this);
|
|
85
|
+
};
|
|
86
|
+
this.#getEnabled = () => {
|
|
87
|
+
return !!parseFunctionOrValue(this.options.enabled, this);
|
|
88
|
+
};
|
|
89
|
+
this.#getWait = () => {
|
|
90
|
+
return parseFunctionOrValue(this.options.wait, this);
|
|
91
|
+
};
|
|
72
92
|
this.maybeExecute = (...args) => {
|
|
73
93
|
if (!this.#getEnabled()) return void 0;
|
|
74
94
|
this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
|
|
@@ -88,12 +108,28 @@ var Debouncer = class {
|
|
|
88
108
|
if (this.options.trailing && !_didLeadingExecute) this.#execute(...args);
|
|
89
109
|
}, this.#getWait());
|
|
90
110
|
};
|
|
111
|
+
this.#execute = (...args) => {
|
|
112
|
+
if (!this.#getEnabled()) return void 0;
|
|
113
|
+
this.fn(...args);
|
|
114
|
+
this.#setState({
|
|
115
|
+
executionCount: this.store.state.executionCount + 1,
|
|
116
|
+
isPending: false,
|
|
117
|
+
lastArgs: void 0
|
|
118
|
+
});
|
|
119
|
+
this.options.onExecute?.(args, this);
|
|
120
|
+
};
|
|
91
121
|
this.flush = () => {
|
|
92
122
|
if (this.store.state.isPending && this.store.state.lastArgs) {
|
|
93
123
|
this.#clearTimeout();
|
|
94
124
|
this.#execute(...this.store.state.lastArgs);
|
|
95
125
|
}
|
|
96
126
|
};
|
|
127
|
+
this.#clearTimeout = () => {
|
|
128
|
+
if (this.#timeoutId) {
|
|
129
|
+
clearTimeout(this.#timeoutId);
|
|
130
|
+
this.#timeoutId = void 0;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
97
133
|
this.cancel = () => {
|
|
98
134
|
this.#clearTimeout();
|
|
99
135
|
this.#setState({
|
|
@@ -116,48 +152,17 @@ var Debouncer = class {
|
|
|
116
152
|
this.setOptions(event.payload.options);
|
|
117
153
|
});
|
|
118
154
|
}
|
|
119
|
-
#setState
|
|
120
|
-
this.store.setState((state) => {
|
|
121
|
-
const combinedState = {
|
|
122
|
-
...state,
|
|
123
|
-
...newState
|
|
124
|
-
};
|
|
125
|
-
const { isPending } = combinedState;
|
|
126
|
-
return {
|
|
127
|
-
...combinedState,
|
|
128
|
-
status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
|
|
129
|
-
};
|
|
130
|
-
});
|
|
131
|
-
emitChange("Debouncer", this);
|
|
132
|
-
};
|
|
155
|
+
#setState;
|
|
133
156
|
/**
|
|
134
157
|
* Returns the current enabled state of the debouncer
|
|
135
158
|
*/
|
|
136
|
-
#getEnabled
|
|
137
|
-
return !!parseFunctionOrValue(this.options.enabled, this);
|
|
138
|
-
};
|
|
159
|
+
#getEnabled;
|
|
139
160
|
/**
|
|
140
161
|
* Returns the current wait time in milliseconds
|
|
141
162
|
*/
|
|
142
|
-
#getWait
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
#execute = (...args) => {
|
|
146
|
-
if (!this.#getEnabled()) return void 0;
|
|
147
|
-
this.fn(...args);
|
|
148
|
-
this.#setState({
|
|
149
|
-
executionCount: this.store.state.executionCount + 1,
|
|
150
|
-
isPending: false,
|
|
151
|
-
lastArgs: void 0
|
|
152
|
-
});
|
|
153
|
-
this.options.onExecute?.(args, this);
|
|
154
|
-
};
|
|
155
|
-
#clearTimeout = () => {
|
|
156
|
-
if (this.#timeoutId) {
|
|
157
|
-
clearTimeout(this.#timeoutId);
|
|
158
|
-
this.#timeoutId = void 0;
|
|
159
|
-
}
|
|
160
|
-
};
|
|
163
|
+
#getWait;
|
|
164
|
+
#execute;
|
|
165
|
+
#clearTimeout;
|
|
161
166
|
};
|
|
162
167
|
/**
|
|
163
168
|
* Creates a debounced function that delays invoking the provided function until after a specified wait time.
|
package/dist/debouncer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debouncer.js","names":["#getEnabled","#setState","#execute","#timeoutId","#getWait","#clearTimeout"],"sources":["../src/debouncer.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 DebouncerState<TFn extends AnyFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the debouncer 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 * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultDebouncerState<\n TFn extends AnyFunction,\n>(): DebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Initial state for the debouncer\n */\n initialState?: Partial<DebouncerState<TFn>>\n /**\n * A key to identify the debouncer.\n * If provided, the debouncer 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 * The first call will execute immediately and the rest will wait the delay.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds before executing the function.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.\n */\nexport function debouncerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<DebouncerOptions<TFn>> = Partial<\n DebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a debounced function.\n *\n * Debouncing ensures that a function is only executed after a certain amount of time has passed\n * since its last invocation. This is useful for handling frequent events like window resizing,\n * scroll events, or input changes where you want to limit the rate of execution.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The debounced function can be configured to execute either at the start of the delay period\n * (leading edge) or at the end (trailing edge, default). Each new call during the wait period\n * will reset the timer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via `debouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\n *\n * // Will only save after 500ms of no new input\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class Debouncer<TFn extends AnyFunction> {\n readonly store: Store<Readonly<DebouncerState<TFn>>> = new Store(\n getDefaultDebouncerState<TFn>(),\n )\n key: string | undefined\n options: DebouncerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: DebouncerOptions<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-Debouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<DebouncerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<DebouncerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions = (newOptions: Partial<DebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<DebouncerState<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('Debouncer', this)\n }\n\n /**\n * Returns the current enabled state of the debouncer\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 debounced function\n * If a call is already in progress, it will be queued\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n _didLeadingExecute = true\n this.#execute(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (this.options.trailing) {\n this.#setState({ isPending: true, lastArgs: args })\n }\n\n // Clear any existing timeout\n if (this.#timeoutId) clearTimeout(this.#timeoutId)\n\n // Set new timeout that will reset canLeadingExecute and execute trailing only if enabled and did not execute leading\n this.#timeoutId = setTimeout(() => {\n this.#setState({ canLeadingExecute: true })\n if (this.options.trailing && !_didLeadingExecute) {\n this.#execute(...args)\n }\n }, this.#getWait())\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, 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.#clearTimeout() // clear any pending timeout\n this.#execute(...this.store.state.lastArgs) // execute immediately\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 execution\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n canLeadingExecute: true,\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultDebouncerState<TFn>())\n }\n}\n\n/**\n * Creates a debounced function that delays invoking the provided function until after a specified wait time.\n * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * If leading option is true, the function will execute immediately on the first call, then wait the delay\n * before allowing another execution.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via the underlying Debouncer 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 * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute\n}\n"],"mappings":";;;;;AAgCA,SAAS,2BAEgB;AACvB,QAAO;EACL,mBAAmB;EACnB,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,QAAQ;EACR,mBAAmB;EACpB;;;;;AAgDH,SAAgB,iBAKd,SAA6B;AAC7B,QAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,SA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;GACH,GAAG;GACJ;AACD,QAAKA,SAAU,KAAK,QAAQ,gBAAgB,EAAE,CAAC;AAE/C,MAAI,KAAK,IACP,kBAAiB,GAAG,gBAAgB,UAAU;AAC5C,OAAI,MAAM,QAAQ,QAAQ,KAAK,IAAK;AACpC,SAAKA,SACH,MAAM,QAAQ,MAAM,MACrB;AACD,QAAK,WAAW,MAAM,QAAQ,QAA0C;IACxE;;CAgBN,aAAa,aAAiD;AAC5D,OAAK,MAAM,UAAU,UAAU;GAC7B,MAAM,gBAAgB;IACpB,GAAG;IACH,GAAG;IACJ;GACD,MAAM,EAAE,cAAc;AACtB,UAAO;IACL,GAAG;IACH,QAAQ,CAAC,MAAKD,YAAa,GACvB,aACA,YACE,YACA;IACP;IACD;AACF,aAAW,aAAa,KAAK;;;;;CAM/B,oBAA6B;AAC3B,SAAO,CAAC,CAAC,qBAAqB,KAAK,QAAQ,SAAS,KAAK;;;;;CAM3D,iBAAyB;AACvB,SAAO,qBAAqB,KAAK,QAAQ,MAAM,KAAK;;CAwCtD,YAAY,GAAG,SAAgC;AAC7C,MAAI,CAAC,MAAKA,YAAa,CAAE,QAAO;AAChC,OAAK,GAAG,GAAG,KAAK;AAChB,QAAKC,SAAU;GACb,gBAAgB,KAAK,MAAM,MAAM,iBAAiB;GAClD,WAAW;GACX,UAAU;GACX,CAAC;AACF,OAAK,QAAQ,YAAY,MAAM,KAAK;;CAatC,sBAA4B;AAC1B,MAAI,MAAKE,WAAY;AACnB,gBAAa,MAAKA,UAAW;AAC7B,SAAKA,YAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDxB,SAAgB,SACd,IACA,gBACoC;AAEpC,QADkB,IAAI,UAAU,IAAI,eAAe,CAClC"}
|
|
1
|
+
{"version":3,"file":"debouncer.js","names":["#getEnabled","#setState","#execute","#timeoutId","#getWait","#clearTimeout"],"sources":["../src/debouncer.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 DebouncerState<TFn extends AnyFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the debouncer 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 * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultDebouncerState<\n TFn extends AnyFunction,\n>(): DebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Initial state for the debouncer\n */\n initialState?: Partial<DebouncerState<TFn>>\n /**\n * A key to identify the debouncer.\n * If provided, the debouncer 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 * The first call will execute immediately and the rest will wait the delay.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds before executing the function.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.\n */\nexport function debouncerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<DebouncerOptions<TFn>> = Partial<\n DebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a debounced function.\n *\n * Debouncing ensures that a function is only executed after a certain amount of time has passed\n * since its last invocation. This is useful for handling frequent events like window resizing,\n * scroll events, or input changes where you want to limit the rate of execution.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The debounced function can be configured to execute either at the start of the delay period\n * (leading edge) or at the end (trailing edge, default). Each new call during the wait period\n * will reset the timer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via `debouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\n *\n * // Will only save after 500ms of no new input\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class Debouncer<TFn extends AnyFunction> {\n readonly store: Store<Readonly<DebouncerState<TFn>>> = new Store(\n getDefaultDebouncerState<TFn>(),\n )\n key: string | undefined\n options: DebouncerOptions<TFn>\n #timeoutId: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: DebouncerOptions<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-Debouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<DebouncerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<DebouncerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions = (newOptions: Partial<DebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<DebouncerState<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('Debouncer', this)\n }\n\n /**\n * Returns the current enabled state of the debouncer\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 debounced function\n * If a call is already in progress, it will be queued\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n _didLeadingExecute = true\n this.#execute(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (this.options.trailing) {\n this.#setState({ isPending: true, lastArgs: args })\n }\n\n // Clear any existing timeout\n if (this.#timeoutId) clearTimeout(this.#timeoutId)\n\n // Set new timeout that will reset canLeadingExecute and execute trailing only if enabled and did not execute leading\n this.#timeoutId = setTimeout(() => {\n this.#setState({ canLeadingExecute: true })\n if (this.options.trailing && !_didLeadingExecute) {\n this.#execute(...args)\n }\n }, this.#getWait())\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, 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.#clearTimeout() // clear any pending timeout\n this.#execute(...this.store.state.lastArgs) // execute immediately\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 execution\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n canLeadingExecute: true,\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultDebouncerState<TFn>())\n }\n}\n\n/**\n * Creates a debounced function that delays invoking the provided function until after a specified wait time.\n * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * If leading option is true, the function will execute immediately on the first call, then wait the delay\n * before allowing another execution.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via the underlying Debouncer 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 * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute\n}\n"],"m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;AAEpC,QADkB,IAAI,UAAU,IAAI,eAAe,CAClC"}
|
package/dist/queuer.cjs
CHANGED
|
@@ -113,16 +113,61 @@ const defaultOptions = {
|
|
|
113
113
|
* ```
|
|
114
114
|
*/
|
|
115
115
|
var Queuer = class {
|
|
116
|
-
#timeoutId
|
|
116
|
+
#timeoutId;
|
|
117
117
|
constructor(fn, initialOptions = {}) {
|
|
118
118
|
this.fn = fn;
|
|
119
119
|
this.store = new _tanstack_store.Store(getDefaultQueuerState());
|
|
120
|
+
this.#timeoutId = null;
|
|
120
121
|
this.setOptions = (newOptions) => {
|
|
121
122
|
this.options = {
|
|
122
123
|
...this.options,
|
|
123
124
|
...newOptions
|
|
124
125
|
};
|
|
125
126
|
};
|
|
127
|
+
this.#setState = (newState) => {
|
|
128
|
+
this.store.setState((state) => {
|
|
129
|
+
const combinedState = {
|
|
130
|
+
...state,
|
|
131
|
+
...newState
|
|
132
|
+
};
|
|
133
|
+
const { items, isRunning } = combinedState;
|
|
134
|
+
const size = items.length;
|
|
135
|
+
const isFull = size >= (this.options.maxSize ?? Infinity);
|
|
136
|
+
const isEmpty = size === 0;
|
|
137
|
+
const isIdle = isRunning && isEmpty;
|
|
138
|
+
const status = isIdle ? "idle" : isRunning ? "running" : "stopped";
|
|
139
|
+
return {
|
|
140
|
+
...combinedState,
|
|
141
|
+
isEmpty,
|
|
142
|
+
isFull,
|
|
143
|
+
isIdle,
|
|
144
|
+
size,
|
|
145
|
+
status
|
|
146
|
+
};
|
|
147
|
+
});
|
|
148
|
+
require_event_client.emitChange("Queuer", this);
|
|
149
|
+
};
|
|
150
|
+
this.#getWait = () => {
|
|
151
|
+
return require_utils.parseFunctionOrValue(this.options.wait ?? 0, this);
|
|
152
|
+
};
|
|
153
|
+
this.#tick = () => {
|
|
154
|
+
if (!this.store.state.isRunning) {
|
|
155
|
+
this.#setState({ pendingTick: false });
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
this.#setState({ pendingTick: true });
|
|
159
|
+
this.#checkExpiredItems();
|
|
160
|
+
while (this.store.state.items.length > 0) {
|
|
161
|
+
if (this.execute(this.options.getItemsFrom ?? "front") === void 0) break;
|
|
162
|
+
const wait = this.#getWait();
|
|
163
|
+
if (wait > 0) {
|
|
164
|
+
this.#timeoutId = setTimeout(() => this.#tick(), wait);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
this.#tick();
|
|
168
|
+
}
|
|
169
|
+
this.#setState({ pendingTick: false });
|
|
170
|
+
};
|
|
126
171
|
this.addItem = (item, position = this.options.addItemsTo ?? "back", runOnItemsChange = true) => {
|
|
127
172
|
this.#setState({ addItemCount: this.store.state.addItemCount + 1 });
|
|
128
173
|
if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {
|
|
@@ -181,6 +226,11 @@ var Queuer = class {
|
|
|
181
226
|
if (item !== void 0) this.options.onItemsChange?.(this);
|
|
182
227
|
return item;
|
|
183
228
|
};
|
|
229
|
+
this.#getAllItems = () => {
|
|
230
|
+
const items = this.peekAllItems();
|
|
231
|
+
this.clear();
|
|
232
|
+
return items;
|
|
233
|
+
};
|
|
184
234
|
this.execute = (position) => {
|
|
185
235
|
const item = this.getNextItem(position);
|
|
186
236
|
if (item !== void 0) {
|
|
@@ -200,6 +250,35 @@ var Queuer = class {
|
|
|
200
250
|
this.clear();
|
|
201
251
|
batchFunction(items);
|
|
202
252
|
};
|
|
253
|
+
this.#checkExpiredItems = () => {
|
|
254
|
+
if ((this.options.expirationDuration ?? Infinity) === Infinity && this.options.getIsExpired === defaultOptions.getIsExpired) return;
|
|
255
|
+
const now = Date.now();
|
|
256
|
+
const expiredIndices = [];
|
|
257
|
+
for (let i = 0; i < this.store.state.items.length; i++) {
|
|
258
|
+
const timestamp = this.store.state.itemTimestamps[i];
|
|
259
|
+
if (timestamp === void 0) continue;
|
|
260
|
+
const item = this.store.state.items[i];
|
|
261
|
+
if (item === void 0) continue;
|
|
262
|
+
if (this.options.getIsExpired !== defaultOptions.getIsExpired ? this.options.getIsExpired(item, timestamp) : now - timestamp > (this.options.expirationDuration ?? Infinity)) expiredIndices.push(i);
|
|
263
|
+
}
|
|
264
|
+
for (let i = expiredIndices.length - 1; i >= 0; i--) {
|
|
265
|
+
const index = expiredIndices[i];
|
|
266
|
+
if (index === void 0) continue;
|
|
267
|
+
const expiredItem = this.store.state.items[index];
|
|
268
|
+
if (expiredItem === void 0) continue;
|
|
269
|
+
const newItems = [...this.store.state.items];
|
|
270
|
+
const newTimestamps = [...this.store.state.itemTimestamps];
|
|
271
|
+
newItems.splice(index, 1);
|
|
272
|
+
newTimestamps.splice(index, 1);
|
|
273
|
+
this.#setState({
|
|
274
|
+
items: newItems,
|
|
275
|
+
itemTimestamps: newTimestamps,
|
|
276
|
+
expirationCount: this.store.state.expirationCount + 1
|
|
277
|
+
});
|
|
278
|
+
this.options.onExpire?.(expiredItem, this);
|
|
279
|
+
}
|
|
280
|
+
if (expiredIndices.length > 0) this.options.onItemsChange?.(this);
|
|
281
|
+
};
|
|
203
282
|
this.peekNextItem = (position = "front") => {
|
|
204
283
|
if (position === "front") return this.store.state.items[0];
|
|
205
284
|
return this.store.state.items[this.store.state.items.length - 1];
|
|
@@ -218,6 +297,12 @@ var Queuer = class {
|
|
|
218
297
|
pendingTick: false
|
|
219
298
|
});
|
|
220
299
|
};
|
|
300
|
+
this.#clearTimeout = () => {
|
|
301
|
+
if (this.#timeoutId) {
|
|
302
|
+
clearTimeout(this.#timeoutId);
|
|
303
|
+
this.#timeoutId = null;
|
|
304
|
+
}
|
|
305
|
+
};
|
|
221
306
|
this.clear = () => {
|
|
222
307
|
this.#setState({
|
|
223
308
|
items: [],
|
|
@@ -252,101 +337,23 @@ var Queuer = class {
|
|
|
252
337
|
this.setOptions(event.payload.options);
|
|
253
338
|
});
|
|
254
339
|
}
|
|
255
|
-
#setState
|
|
256
|
-
this.store.setState((state) => {
|
|
257
|
-
const combinedState = {
|
|
258
|
-
...state,
|
|
259
|
-
...newState
|
|
260
|
-
};
|
|
261
|
-
const { items, isRunning } = combinedState;
|
|
262
|
-
const size = items.length;
|
|
263
|
-
const isFull = size >= (this.options.maxSize ?? Infinity);
|
|
264
|
-
const isEmpty = size === 0;
|
|
265
|
-
const isIdle = isRunning && isEmpty;
|
|
266
|
-
const status = isIdle ? "idle" : isRunning ? "running" : "stopped";
|
|
267
|
-
return {
|
|
268
|
-
...combinedState,
|
|
269
|
-
isEmpty,
|
|
270
|
-
isFull,
|
|
271
|
-
isIdle,
|
|
272
|
-
size,
|
|
273
|
-
status
|
|
274
|
-
};
|
|
275
|
-
});
|
|
276
|
-
require_event_client.emitChange("Queuer", this);
|
|
277
|
-
};
|
|
340
|
+
#setState;
|
|
278
341
|
/**
|
|
279
342
|
* Returns the current wait time (in milliseconds) between processing items.
|
|
280
343
|
* If a function is provided, it is called with the queuer instance.
|
|
281
344
|
*/
|
|
282
|
-
#getWait
|
|
283
|
-
return require_utils.parseFunctionOrValue(this.options.wait ?? 0, this);
|
|
284
|
-
};
|
|
345
|
+
#getWait;
|
|
285
346
|
/**
|
|
286
347
|
* Processes items in the queue up to the wait interval. Internal use only.
|
|
287
348
|
*/
|
|
288
|
-
#tick
|
|
289
|
-
|
|
290
|
-
this.#setState({ pendingTick: false });
|
|
291
|
-
return;
|
|
292
|
-
}
|
|
293
|
-
this.#setState({ pendingTick: true });
|
|
294
|
-
this.#checkExpiredItems();
|
|
295
|
-
while (this.store.state.items.length > 0) {
|
|
296
|
-
if (this.execute(this.options.getItemsFrom ?? "front") === void 0) break;
|
|
297
|
-
const wait = this.#getWait();
|
|
298
|
-
if (wait > 0) {
|
|
299
|
-
this.#timeoutId = setTimeout(() => this.#tick(), wait);
|
|
300
|
-
return;
|
|
301
|
-
}
|
|
302
|
-
this.#tick();
|
|
303
|
-
}
|
|
304
|
-
this.#setState({ pendingTick: false });
|
|
305
|
-
};
|
|
306
|
-
#getAllItems = () => {
|
|
307
|
-
const items = this.peekAllItems();
|
|
308
|
-
this.clear();
|
|
309
|
-
return items;
|
|
310
|
-
};
|
|
349
|
+
#tick;
|
|
350
|
+
#getAllItems;
|
|
311
351
|
/**
|
|
312
352
|
* Checks for expired items in the queue and removes them. Calls onExpire for each expired item.
|
|
313
353
|
* Internal use only.
|
|
314
354
|
*/
|
|
315
|
-
#checkExpiredItems
|
|
316
|
-
|
|
317
|
-
const now = Date.now();
|
|
318
|
-
const expiredIndices = [];
|
|
319
|
-
for (let i = 0; i < this.store.state.items.length; i++) {
|
|
320
|
-
const timestamp = this.store.state.itemTimestamps[i];
|
|
321
|
-
if (timestamp === void 0) continue;
|
|
322
|
-
const item = this.store.state.items[i];
|
|
323
|
-
if (item === void 0) continue;
|
|
324
|
-
if (this.options.getIsExpired !== defaultOptions.getIsExpired ? this.options.getIsExpired(item, timestamp) : now - timestamp > (this.options.expirationDuration ?? Infinity)) expiredIndices.push(i);
|
|
325
|
-
}
|
|
326
|
-
for (let i = expiredIndices.length - 1; i >= 0; i--) {
|
|
327
|
-
const index = expiredIndices[i];
|
|
328
|
-
if (index === void 0) continue;
|
|
329
|
-
const expiredItem = this.store.state.items[index];
|
|
330
|
-
if (expiredItem === void 0) continue;
|
|
331
|
-
const newItems = [...this.store.state.items];
|
|
332
|
-
const newTimestamps = [...this.store.state.itemTimestamps];
|
|
333
|
-
newItems.splice(index, 1);
|
|
334
|
-
newTimestamps.splice(index, 1);
|
|
335
|
-
this.#setState({
|
|
336
|
-
items: newItems,
|
|
337
|
-
itemTimestamps: newTimestamps,
|
|
338
|
-
expirationCount: this.store.state.expirationCount + 1
|
|
339
|
-
});
|
|
340
|
-
this.options.onExpire?.(expiredItem, this);
|
|
341
|
-
}
|
|
342
|
-
if (expiredIndices.length > 0) this.options.onItemsChange?.(this);
|
|
343
|
-
};
|
|
344
|
-
#clearTimeout = () => {
|
|
345
|
-
if (this.#timeoutId) {
|
|
346
|
-
clearTimeout(this.#timeoutId);
|
|
347
|
-
this.#timeoutId = null;
|
|
348
|
-
}
|
|
349
|
-
};
|
|
355
|
+
#checkExpiredItems;
|
|
356
|
+
#clearTimeout;
|
|
350
357
|
};
|
|
351
358
|
/**
|
|
352
359
|
* Creates a queue that processes items immediately upon addition.
|