@tanstack/pacer 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/cjs/async-debouncer.cjs +112 -63
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +66 -25
  4. package/dist/cjs/async-queuer.cjs +198 -124
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +91 -49
  7. package/dist/cjs/async-rate-limiter.cjs +83 -55
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +55 -28
  10. package/dist/cjs/async-throttler.cjs +121 -70
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +75 -25
  13. package/dist/cjs/debouncer.cjs +45 -23
  14. package/dist/cjs/debouncer.cjs.map +1 -1
  15. package/dist/cjs/debouncer.d.cts +27 -12
  16. package/dist/cjs/index.cjs +2 -0
  17. package/dist/cjs/index.cjs.map +1 -1
  18. package/dist/cjs/index.d.cts +2 -0
  19. package/dist/cjs/queuer.cjs +161 -101
  20. package/dist/cjs/queuer.cjs.map +1 -1
  21. package/dist/cjs/queuer.d.cts +80 -38
  22. package/dist/cjs/rate-limiter.cjs +52 -44
  23. package/dist/cjs/rate-limiter.cjs.map +1 -1
  24. package/dist/cjs/rate-limiter.d.cts +38 -46
  25. package/dist/cjs/throttler.cjs +57 -44
  26. package/dist/cjs/throttler.cjs.map +1 -1
  27. package/dist/cjs/throttler.d.cts +35 -23
  28. package/dist/cjs/types.d.cts +8 -0
  29. package/dist/cjs/utils.cjs +13 -0
  30. package/dist/cjs/utils.cjs.map +1 -0
  31. package/dist/cjs/utils.d.cts +1 -0
  32. package/dist/esm/async-debouncer.d.ts +66 -25
  33. package/dist/esm/async-debouncer.js +112 -63
  34. package/dist/esm/async-debouncer.js.map +1 -1
  35. package/dist/esm/async-queuer.d.ts +91 -49
  36. package/dist/esm/async-queuer.js +198 -124
  37. package/dist/esm/async-queuer.js.map +1 -1
  38. package/dist/esm/async-rate-limiter.d.ts +55 -28
  39. package/dist/esm/async-rate-limiter.js +83 -55
  40. package/dist/esm/async-rate-limiter.js.map +1 -1
  41. package/dist/esm/async-throttler.d.ts +75 -25
  42. package/dist/esm/async-throttler.js +121 -70
  43. package/dist/esm/async-throttler.js.map +1 -1
  44. package/dist/esm/debouncer.d.ts +27 -12
  45. package/dist/esm/debouncer.js +45 -23
  46. package/dist/esm/debouncer.js.map +1 -1
  47. package/dist/esm/index.d.ts +2 -0
  48. package/dist/esm/index.js +2 -0
  49. package/dist/esm/index.js.map +1 -1
  50. package/dist/esm/queuer.d.ts +80 -38
  51. package/dist/esm/queuer.js +161 -101
  52. package/dist/esm/queuer.js.map +1 -1
  53. package/dist/esm/rate-limiter.d.ts +38 -46
  54. package/dist/esm/rate-limiter.js +52 -44
  55. package/dist/esm/rate-limiter.js.map +1 -1
  56. package/dist/esm/throttler.d.ts +35 -23
  57. package/dist/esm/throttler.js +57 -44
  58. package/dist/esm/throttler.js.map +1 -1
  59. package/dist/esm/types.d.ts +8 -0
  60. package/dist/esm/utils.d.ts +1 -0
  61. package/dist/esm/utils.js +13 -0
  62. package/dist/esm/utils.js.map +1 -0
  63. package/package.json +8 -1
  64. package/src/async-debouncer.ts +157 -88
  65. package/src/async-queuer.ts +266 -148
  66. package/src/async-rate-limiter.ts +123 -83
  67. package/src/async-throttler.ts +173 -89
  68. package/src/debouncer.ts +71 -42
  69. package/src/index.ts +2 -0
  70. package/src/queuer.ts +219 -114
  71. package/src/rate-limiter.ts +74 -88
  72. package/src/throttler.ts +83 -65
  73. package/src/types.ts +9 -0
  74. package/src/utils.ts +13 -0
@@ -3,20 +3,27 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const defaultOptions = {
4
4
  enabled: true,
5
5
  leading: false,
6
- trailing: true,
7
6
  onError: () => {
8
7
  },
8
+ onSettled: () => {
9
+ },
10
+ onSuccess: () => {
11
+ },
12
+ trailing: true,
9
13
  wait: 0
10
14
  };
11
15
  class AsyncDebouncer {
12
16
  constructor(fn, initialOptions) {
13
17
  this.fn = fn;
14
- this.abortController = null;
15
- this.executionCount = 0;
16
- this.isExecuting = false;
17
- this.timeoutId = null;
18
- this.canLeadingExecute = true;
19
- this.options = {
18
+ this._abortController = null;
19
+ this._canLeadingExecute = true;
20
+ this._errorCount = 0;
21
+ this._isExecuting = false;
22
+ this._isPending = false;
23
+ this._settleCount = 0;
24
+ this._successCount = 0;
25
+ this._timeoutId = null;
26
+ this._options = {
20
27
  ...defaultOptions,
21
28
  ...initialOptions
22
29
  };
@@ -26,78 +33,120 @@ class AsyncDebouncer {
26
33
  * Returns the new options state
27
34
  */
28
35
  setOptions(newOptions) {
29
- this.options = {
30
- ...this.options,
31
- ...newOptions
32
- };
33
- return this.options;
36
+ this._options = { ...this._options, ...newOptions };
37
+ if (!this._options.enabled) {
38
+ this._isPending = false;
39
+ }
34
40
  }
35
41
  /**
36
- * Returns the number of times the function has been executed
42
+ * Returns the current debouncer options
37
43
  */
38
- getExecutionCount() {
39
- return this.executionCount;
40
- }
41
- /**
42
- * Cancels any pending execution
43
- */
44
- cancel() {
45
- if (this.timeoutId) {
46
- clearTimeout(this.timeoutId);
47
- this.timeoutId = null;
48
- }
49
- if (this.abortController) {
50
- this.abortController.abort();
51
- this.abortController = null;
52
- }
53
- this.lastArgs = void 0;
54
- this.canLeadingExecute = true;
44
+ getOptions() {
45
+ return this._options;
55
46
  }
56
47
  /**
57
48
  * Attempts to execute the debounced function
58
49
  * If a call is already in progress, it will be queued
59
50
  */
60
51
  async maybeExecute(...args) {
61
- this.cancel();
62
- this.lastArgs = args;
63
- if (this.options.leading && this.canLeadingExecute) {
64
- this.canLeadingExecute = false;
52
+ this._cancel();
53
+ this._lastArgs = args;
54
+ if (this._options.leading && this._canLeadingExecute) {
55
+ this._canLeadingExecute = false;
65
56
  await this.executeFunction(...args);
57
+ return this._lastResult;
58
+ }
59
+ if (this._options.trailing) {
60
+ this._isPending = true;
66
61
  }
67
62
  return new Promise((resolve) => {
68
- this.timeoutId = setTimeout(async () => {
69
- if (this.isExecuting) {
70
- resolve();
71
- return;
72
- }
73
- this.canLeadingExecute = true;
74
- if (this.options.trailing) {
75
- this.abortController = new AbortController();
76
- try {
77
- this.isExecuting = true;
78
- if (this.lastArgs) {
79
- await this.executeFunction(...this.lastArgs);
80
- }
81
- } catch (error) {
82
- try {
83
- this.options.onError(error);
84
- } catch {
85
- }
86
- } finally {
87
- this.isExecuting = false;
88
- this.abortController = null;
89
- resolve();
90
- }
91
- } else {
92
- resolve();
63
+ this._timeoutId = setTimeout(async () => {
64
+ if (this._options.trailing && this._lastArgs) {
65
+ await this.executeFunction(...this._lastArgs);
93
66
  }
94
- }, this.options.wait);
67
+ this._canLeadingExecute = true;
68
+ resolve(this._lastResult);
69
+ }, this._options.wait);
95
70
  });
96
71
  }
97
72
  async executeFunction(...args) {
98
- if (!this.options.enabled) return;
99
- this.executionCount++;
100
- await this.fn(...args);
73
+ if (!this._options.enabled) return void 0;
74
+ this._abortController = new AbortController();
75
+ try {
76
+ this._isExecuting = true;
77
+ this._lastResult = await this.fn(...args);
78
+ this._successCount++;
79
+ this._options.onSuccess(this._lastResult, this);
80
+ } catch (error) {
81
+ this._errorCount++;
82
+ this._options.onError(error, this);
83
+ } finally {
84
+ this._isExecuting = false;
85
+ this._isPending = false;
86
+ this._settleCount++;
87
+ this._abortController = null;
88
+ this._options.onSettled(this);
89
+ }
90
+ return this._lastResult;
91
+ }
92
+ /**
93
+ * Cancel without resetting _canLeadingExecute
94
+ */
95
+ _cancel() {
96
+ if (this._timeoutId) {
97
+ clearTimeout(this._timeoutId);
98
+ this._timeoutId = null;
99
+ }
100
+ if (this._abortController) {
101
+ this._abortController.abort();
102
+ this._abortController = null;
103
+ }
104
+ this._lastArgs = void 0;
105
+ this._isPending = false;
106
+ this._isExecuting = false;
107
+ }
108
+ /**
109
+ * Cancels any pending execution or aborts any execution in progress
110
+ */
111
+ cancel() {
112
+ this._canLeadingExecute = true;
113
+ this._cancel();
114
+ }
115
+ /**
116
+ * Returns the last result of the debounced function
117
+ */
118
+ getLastResult() {
119
+ return this._lastResult;
120
+ }
121
+ /**
122
+ * Returns the number of times the function has been executed successfully
123
+ */
124
+ getSuccessCount() {
125
+ return this._successCount;
126
+ }
127
+ /**
128
+ * Returns the number of times the function has settled (completed or errored)
129
+ */
130
+ getSettleCount() {
131
+ return this._settleCount;
132
+ }
133
+ /**
134
+ * Returns the number of times the function has errored
135
+ */
136
+ getErrorCount() {
137
+ return this._errorCount;
138
+ }
139
+ /**
140
+ * Returns `true` if there is a pending execution queued up for trailing execution
141
+ */
142
+ getIsPending() {
143
+ return this._options.enabled && this._isPending;
144
+ }
145
+ /**
146
+ * Returns `true` if there is currently an execution in progress
147
+ */
148
+ getIsExecuting() {
149
+ return this._isExecuting;
101
150
  }
102
151
  }
103
152
  function asyncDebounce(fn, initialOptions) {
@@ -1 +1 @@
1
- {"version":3,"file":"async-debouncer.cjs","sources":["../../src/async-debouncer.ts"],"sourcesContent":["/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\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 to wait after the last call before executing\n * Defaults to 0ms\n */\n wait: number\n /**\n * Optional error handler for when the debounced function throws\n */\n onError?: (error: unknown) => void\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions> = {\n enabled: true,\n leading: false,\n trailing: true,\n onError: () => {},\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * @example\n * ```ts\n * const debouncer = new AsyncDebouncer(async (value: string) => {\n * await searchAPI(value);\n * }, { wait: 500 });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class AsyncDebouncer<\n TFn extends (...args: Array<any>) => Promise<any>,\n TArgs extends Parameters<TFn>,\n> {\n private abortController: AbortController | null = null\n private executionCount = 0\n private isExecuting = false\n private lastArgs: TArgs | undefined\n private options: Required<AsyncDebouncerOptions>\n private timeoutId: ReturnType<typeof setTimeout> | null = null\n private canLeadingExecute = true\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<AsyncDebouncerOptions>,\n ): Required<AsyncDebouncerOptions> {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this.executionCount\n }\n\n /**\n * Cancels any pending execution\n */\n cancel(): void {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = null\n }\n if (this.abortController) {\n this.abortController.abort()\n this.abortController = null\n }\n this.lastArgs = undefined\n this.canLeadingExecute = true\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n async maybeExecute(...args: TArgs): Promise<void> {\n this.cancel()\n this.lastArgs = args\n\n // Handle leading execution\n if (this.options.leading && this.canLeadingExecute) {\n this.canLeadingExecute = false\n await this.executeFunction(...args)\n }\n\n return new Promise((resolve) => {\n this.timeoutId = setTimeout(async () => {\n if (this.isExecuting) {\n resolve()\n return\n }\n\n this.canLeadingExecute = true\n // Execute trailing only if enabled\n if (this.options.trailing) {\n this.abortController = new AbortController()\n try {\n this.isExecuting = true\n if (this.lastArgs) {\n await this.executeFunction(...this.lastArgs)\n }\n } catch (error) {\n try {\n this.options.onError(error)\n } catch {\n // Ignore errors from error handler\n }\n } finally {\n this.isExecuting = false\n this.abortController = null\n resolve()\n }\n } else {\n resolve()\n }\n }, this.options.wait)\n })\n }\n\n private async executeFunction(...args: TArgs): Promise<void> {\n if (!this.options.enabled) return\n this.executionCount++\n await this.fn(...args)\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * await saveToAPI(value);\n * }, { wait: 1000 });\n *\n * // Will only execute once, 1 second after the last call\n * await debounced(\"first\"); // Cancelled\n * await debounced(\"second\"); // Cancelled\n * await debounced(\"third\"); // Executes after 1s\n * ```\n */\nexport function asyncDebounce<\n TFn extends (...args: Array<any>) => Promise<any>,\n>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions, 'enabled'>) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":";;AA8BA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,MAAM;AACR;AAwBO,MAAM,eAGX;AAAA,EASA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,kBAA0C;AAClD,SAAQ,iBAAiB;AACzB,SAAQ,cAAc;AAGtB,SAAQ,YAAkD;AAC1D,SAAQ,oBAAoB;AAM1B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IACL;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AAAA,MACV,GACC,KAAK,QAAQ,IAAI;AAAA,IAAA,CACrB;AAAA,EAAA;AAAA,EAGH,MAAc,mBAAmB,MAA4B;AACvD,QAAA,CAAC,KAAK,QAAQ,QAAS;AACtB,SAAA;AACC,UAAA,KAAK,GAAG,GAAG,IAAI;AAAA,EAAA;AAEzB;AAmBgB,SAAA,cAEd,IAAS,gBAAwD;AACjE,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}
1
+ {"version":3,"file":"async-debouncer.cjs","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws\n */\n onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<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 to wait after the last call before executing\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions<any>> = {\n enabled: true,\n leading: false,\n onError: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * await searchAPI(value);\n * }, { wait: 500 });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * inputElement.addEventListener('input', () => {\n * asyncDebouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class AsyncDebouncer<TFn extends AnyAsyncFunction> {\n private _abortController: AbortController | null = null\n private _canLeadingExecute = true\n private _errorCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastResult: ReturnType<TFn> | undefined\n private _options: Required<AsyncDebouncerOptions<TFn>>\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<AsyncDebouncerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this._cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n // Handle trailing execution\n if (this._options.trailing) {\n this._isPending = true\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this._options.trailing && this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n\n // Reset state and resolve\n this._canLeadingExecute = true\n resolve(this._lastResult)\n }, this._options.wait)\n })\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError(error, this)\n } finally {\n this._isExecuting = false\n this._isPending = false\n this._settleCount++\n this._abortController = null\n this._options.onSettled(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancel without resetting _canLeadingExecute\n */\n private _cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._isPending = false\n this._isExecuting = false\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n this._canLeadingExecute = true\n this._cancel()\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns `true` if there is a pending execution queued up for trailing execution\n */\n getIsPending(): boolean {\n return this._options.enabled && this._isPending\n }\n\n /**\n * Returns `true` if there is currently an execution in progress\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * await saveToAPI(value);\n * }, { wait: 1000 });\n *\n * // Will only execute once, 1 second after the last call\n * await debounced(\"first\"); // Cancelled\n * await debounced(\"second\"); // Cancelled\n * await debounced(\"third\"); // Executes after 1s\n * ```\n */\nexport function asyncDebounce<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: Omit<AsyncDebouncerOptions<TFn>, 'enabled'>,\n) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":";;AAwCA,MAAM,iBAAuD;AAAA,EAC3D,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AAwBO,MAAM,eAA6C;AAAA,EAaxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAbV,SAAQ,mBAA2C;AACnD,SAAQ,qBAAqB;AAC7B,SAAQ,cAAc;AACtB,SAAQ,eAAe;AACvB,SAAQ,aAAa;AAIrB,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,aAAoC;AAM1C,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAuD;AAChE,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAG9C,QAAA,CAAC,KAAK,SAAS,SAAS;AAC1B,WAAK,aAAa;AAAA,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAMF,aAAmD;AACjD,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,MAAM,gBACD,MACmC;AACtC,SAAK,QAAQ;AACb,SAAK,YAAY;AAGjB,QAAI,KAAK,SAAS,WAAW,KAAK,oBAAoB;AACpD,WAAK,qBAAqB;AACpB,YAAA,K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AAA;AAAA;AAAA,EAMf,gBAA6C;AAC3C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,SAAS,WAAW,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAmBgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}
@@ -1,7 +1,8 @@
1
+ import { AnyAsyncFunction } from './types.cjs';
1
2
  /**
2
3
  * Options for configuring an async debounced function
3
4
  */
4
- export interface AsyncDebouncerOptions {
5
+ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
5
6
  /**
6
7
  * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
7
8
  * Defaults to true.
@@ -12,6 +13,18 @@ export interface AsyncDebouncerOptions {
12
13
  * Defaults to false.
13
14
  */
14
15
  leading?: boolean;
16
+ /**
17
+ * Optional error handler for when the debounced function throws
18
+ */
19
+ onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void;
20
+ /**
21
+ * Optional callback to call when the debounced function is executed
22
+ */
23
+ onSettled?: (debouncer: AsyncDebouncer<TFn>) => void;
24
+ /**
25
+ * Optional callback to call when the debounced function is executed
26
+ */
27
+ onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void;
15
28
  /**
16
29
  * Whether to execute on the trailing edge of the timeout.
17
30
  * Defaults to true.
@@ -22,10 +35,6 @@ export interface AsyncDebouncerOptions {
22
35
  * Defaults to 0ms
23
36
  */
24
37
  wait: number;
25
- /**
26
- * Optional error handler for when the debounced function throws
27
- */
28
- onError?: (error: unknown) => void;
29
38
  }
30
39
  /**
31
40
  * A class that creates an async debounced function.
@@ -39,45 +48,77 @@ export interface AsyncDebouncerOptions {
39
48
  *
40
49
  * @example
41
50
  * ```ts
42
- * const debouncer = new AsyncDebouncer(async (value: string) => {
51
+ * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
43
52
  * await searchAPI(value);
44
53
  * }, { wait: 500 });
45
54
  *
46
55
  * // Called on each keystroke but only executes after 500ms of no typing
47
56
  * inputElement.addEventListener('input', () => {
48
- * debouncer.maybeExecute(inputElement.value);
57
+ * asyncDebouncer.maybeExecute(inputElement.value);
49
58
  * });
50
59
  * ```
51
60
  */
52
- export declare class AsyncDebouncer<TFn extends (...args: Array<any>) => Promise<any>, TArgs extends Parameters<TFn>> {
61
+ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
53
62
  private fn;
54
- private abortController;
55
- private executionCount;
56
- private isExecuting;
57
- private lastArgs;
58
- private options;
59
- private timeoutId;
60
- private canLeadingExecute;
61
- constructor(fn: TFn, initialOptions: AsyncDebouncerOptions);
63
+ private _abortController;
64
+ private _canLeadingExecute;
65
+ private _errorCount;
66
+ private _isExecuting;
67
+ private _isPending;
68
+ private _lastArgs;
69
+ private _lastResult;
70
+ private _options;
71
+ private _settleCount;
72
+ private _successCount;
73
+ private _timeoutId;
74
+ constructor(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>);
62
75
  /**
63
76
  * Updates the debouncer options
64
77
  * Returns the new options state
65
78
  */
66
- setOptions(newOptions: Partial<AsyncDebouncerOptions>): Required<AsyncDebouncerOptions>;
79
+ setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void;
67
80
  /**
68
- * Returns the number of times the function has been executed
81
+ * Returns the current debouncer options
69
82
  */
70
- getExecutionCount(): number;
71
- /**
72
- * Cancels any pending execution
73
- */
74
- cancel(): void;
83
+ getOptions(): Required<AsyncDebouncerOptions<TFn>>;
75
84
  /**
76
85
  * Attempts to execute the debounced function
77
86
  * If a call is already in progress, it will be queued
78
87
  */
79
- maybeExecute(...args: TArgs): Promise<void>;
88
+ maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
80
89
  private executeFunction;
90
+ /**
91
+ * Cancel without resetting _canLeadingExecute
92
+ */
93
+ private _cancel;
94
+ /**
95
+ * Cancels any pending execution or aborts any execution in progress
96
+ */
97
+ cancel(): void;
98
+ /**
99
+ * Returns the last result of the debounced function
100
+ */
101
+ getLastResult(): ReturnType<TFn> | undefined;
102
+ /**
103
+ * Returns the number of times the function has been executed successfully
104
+ */
105
+ getSuccessCount(): number;
106
+ /**
107
+ * Returns the number of times the function has settled (completed or errored)
108
+ */
109
+ getSettleCount(): number;
110
+ /**
111
+ * Returns the number of times the function has errored
112
+ */
113
+ getErrorCount(): number;
114
+ /**
115
+ * Returns `true` if there is a pending execution queued up for trailing execution
116
+ */
117
+ getIsPending(): boolean;
118
+ /**
119
+ * Returns `true` if there is currently an execution in progress
120
+ */
121
+ getIsExecuting(): boolean;
81
122
  }
82
123
  /**
83
124
  * Creates an async debounced function that delays execution until after a specified wait time.
@@ -96,4 +137,4 @@ export declare class AsyncDebouncer<TFn extends (...args: Array<any>) => Promise
96
137
  * await debounced("third"); // Executes after 1s
97
138
  * ```
98
139
  */
99
- export declare function asyncDebounce<TFn extends (...args: Array<any>) => Promise<any>>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions, 'enabled'>): (...args: Parameters<TFn>) => Promise<void>;
140
+ export declare function asyncDebounce<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;