@tanstack/pacer 0.2.0 → 0.4.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 (65) hide show
  1. package/dist/cjs/async-debouncer.cjs +78 -45
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +60 -24
  4. package/dist/cjs/async-queuer.cjs +53 -3
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +28 -3
  7. package/dist/cjs/async-rate-limiter.cjs +75 -38
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +76 -24
  10. package/dist/cjs/async-throttler.cjs +85 -57
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +66 -25
  13. package/dist/cjs/debouncer.cjs +12 -14
  14. package/dist/cjs/debouncer.cjs.map +1 -1
  15. package/dist/cjs/debouncer.d.cts +10 -9
  16. package/dist/cjs/queuer.cjs +51 -1
  17. package/dist/cjs/queuer.cjs.map +1 -1
  18. package/dist/cjs/queuer.d.cts +30 -1
  19. package/dist/cjs/rate-limiter.cjs +19 -9
  20. package/dist/cjs/rate-limiter.cjs.map +1 -1
  21. package/dist/cjs/rate-limiter.d.cts +31 -11
  22. package/dist/cjs/throttler.cjs +29 -36
  23. package/dist/cjs/throttler.cjs.map +1 -1
  24. package/dist/cjs/throttler.d.cts +16 -17
  25. package/dist/cjs/types.d.cts +2 -6
  26. package/dist/cjs/utils.cjs.map +1 -1
  27. package/dist/cjs/utils.d.cts +1 -1
  28. package/dist/esm/async-debouncer.d.ts +60 -24
  29. package/dist/esm/async-debouncer.js +78 -45
  30. package/dist/esm/async-debouncer.js.map +1 -1
  31. package/dist/esm/async-queuer.d.ts +28 -3
  32. package/dist/esm/async-queuer.js +53 -3
  33. package/dist/esm/async-queuer.js.map +1 -1
  34. package/dist/esm/async-rate-limiter.d.ts +76 -24
  35. package/dist/esm/async-rate-limiter.js +75 -38
  36. package/dist/esm/async-rate-limiter.js.map +1 -1
  37. package/dist/esm/async-throttler.d.ts +66 -25
  38. package/dist/esm/async-throttler.js +85 -57
  39. package/dist/esm/async-throttler.js.map +1 -1
  40. package/dist/esm/debouncer.d.ts +10 -9
  41. package/dist/esm/debouncer.js +12 -14
  42. package/dist/esm/debouncer.js.map +1 -1
  43. package/dist/esm/queuer.d.ts +30 -1
  44. package/dist/esm/queuer.js +51 -1
  45. package/dist/esm/queuer.js.map +1 -1
  46. package/dist/esm/rate-limiter.d.ts +31 -11
  47. package/dist/esm/rate-limiter.js +19 -9
  48. package/dist/esm/rate-limiter.js.map +1 -1
  49. package/dist/esm/throttler.d.ts +16 -17
  50. package/dist/esm/throttler.js +29 -36
  51. package/dist/esm/throttler.js.map +1 -1
  52. package/dist/esm/types.d.ts +2 -6
  53. package/dist/esm/utils.d.ts +1 -1
  54. package/dist/esm/utils.js.map +1 -1
  55. package/package.json +1 -1
  56. package/src/async-debouncer.ts +130 -81
  57. package/src/async-queuer.ts +93 -8
  58. package/src/async-rate-limiter.ts +141 -67
  59. package/src/async-throttler.ts +152 -94
  60. package/src/debouncer.ts +26 -33
  61. package/src/queuer.ts +92 -4
  62. package/src/rate-limiter.ts +56 -32
  63. package/src/throttler.ts +45 -53
  64. package/src/types.ts +2 -10
  65. package/src/utils.ts +1 -1
@@ -2,21 +2,27 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const defaultOptions = {
4
4
  enabled: true,
5
+ leading: true,
5
6
  onError: () => {
6
7
  },
7
- onExecute: () => {
8
+ onSettled: () => {
8
9
  },
10
+ onSuccess: () => {
11
+ },
12
+ trailing: true,
9
13
  wait: 0
10
14
  };
11
15
  class AsyncThrottler {
12
16
  constructor(fn, initialOptions) {
13
17
  this.fn = fn;
14
18
  this._abortController = null;
15
- this._executionCount = 0;
19
+ this._errorCount = 0;
16
20
  this._isExecuting = false;
17
- this._isPending = false;
18
21
  this._lastExecutionTime = 0;
19
22
  this._nextExecutionTime = 0;
23
+ this._settleCount = 0;
24
+ this._successCount = 0;
25
+ this._timeoutId = null;
20
26
  this._options = {
21
27
  ...defaultOptions,
22
28
  ...initialOptions
@@ -27,11 +33,10 @@ class AsyncThrottler {
27
33
  * Returns the new options state
28
34
  */
29
35
  setOptions(newOptions) {
30
- this._options = {
31
- ...this._options,
32
- ...newOptions
33
- };
34
- return this._options;
36
+ this._options = { ...this._options, ...newOptions };
37
+ if (!this._options.enabled) {
38
+ this.cancel();
39
+ }
35
40
  }
36
41
  /**
37
42
  * Returns the current options
@@ -44,72 +49,65 @@ class AsyncThrottler {
44
49
  * If a call is already in progress, it may be blocked or queued depending on the `wait` option
45
50
  */
46
51
  async maybeExecute(...args) {
47
- this._lastArgs = args;
48
- if (this._isPending) return;
49
- this._isPending = true;
52
+ const now = Date.now();
53
+ const timeSinceLastExecution = now - this._lastExecutionTime;
54
+ if (this._options.leading && timeSinceLastExecution >= this._options.wait) {
55
+ await this.executeFunction(...args);
56
+ return this._lastResult;
57
+ } else {
58
+ this._lastArgs = args;
59
+ return new Promise((resolve) => {
60
+ if (this._timeoutId) {
61
+ clearTimeout(this._timeoutId);
62
+ }
63
+ if (this._options.trailing) {
64
+ const _timeSinceLastExecution = this._lastExecutionTime ? now - this._lastExecutionTime : 0;
65
+ const timeoutDuration = this._options.wait - _timeSinceLastExecution;
66
+ this._timeoutId = setTimeout(async () => {
67
+ if (this._lastArgs !== void 0) {
68
+ await this.executeFunction(...this._lastArgs);
69
+ }
70
+ resolve(this._lastResult);
71
+ }, timeoutDuration);
72
+ }
73
+ });
74
+ }
75
+ }
76
+ async executeFunction(...args) {
77
+ if (!this._options.enabled || this._isExecuting) return void 0;
50
78
  this._abortController = new AbortController();
51
- const signal = this._abortController.signal;
52
79
  try {
53
- while (this._isExecuting) {
54
- await this.delay(this._options.wait, signal);
55
- }
56
- while (Date.now() < this._nextExecutionTime) {
57
- await this.delay(this._nextExecutionTime - Date.now(), signal);
58
- }
59
- this._isPending = false;
60
80
  this._isExecuting = true;
61
- await this.executeFunction(...this._lastArgs);
81
+ this._lastResult = await this.fn(...args);
82
+ this._successCount++;
83
+ this._options.onSuccess(this._lastResult, this);
62
84
  } catch (error) {
63
- if (error instanceof Error && error.name === "AbortError") {
64
- return;
65
- }
66
- try {
67
- this._options.onError(error);
68
- } catch {
69
- }
85
+ this._errorCount++;
86
+ this._options.onError(error, this);
70
87
  } finally {
71
- this._lastExecutionTime = Date.now();
72
- this._nextExecutionTime = this._lastExecutionTime + this._options.wait;
73
88
  this._isExecuting = false;
89
+ this._settleCount++;
74
90
  this._abortController = null;
91
+ this._lastExecutionTime = Date.now();
92
+ this._nextExecutionTime = this._lastExecutionTime + this._options.wait;
93
+ this._options.onSettled(this);
75
94
  }
76
- }
77
- delay(ms, signal) {
78
- return new Promise((resolve, reject) => {
79
- const timeout = setTimeout(resolve, ms);
80
- signal.addEventListener(
81
- "abort",
82
- () => {
83
- clearTimeout(timeout);
84
- reject(new Error("AbortError"));
85
- },
86
- { once: true }
87
- );
88
- });
89
- }
90
- async executeFunction(...args) {
91
- if (!this._options.enabled) return;
92
- this._executionCount++;
93
- await this.fn(...args);
94
- this._options.onExecute(this);
95
+ return this._lastResult;
95
96
  }
96
97
  /**
97
- * Cancels any pending execution
98
+ * Cancels any pending execution or aborts any execution in progress
98
99
  */
99
100
  cancel() {
101
+ if (this._timeoutId) {
102
+ clearTimeout(this._timeoutId);
103
+ this._timeoutId = null;
104
+ }
100
105
  if (this._abortController) {
101
106
  this._abortController.abort();
102
107
  this._abortController = null;
103
108
  }
104
- this._isPending = false;
105
109
  this._lastArgs = void 0;
106
110
  }
107
- /**
108
- * Returns the number of times the function has been executed
109
- */
110
- getExecutionCount() {
111
- return this._executionCount;
112
- }
113
111
  /**
114
112
  * Returns the last execution time
115
113
  */
@@ -122,11 +120,41 @@ class AsyncThrottler {
122
120
  getNextExecutionTime() {
123
121
  return this._nextExecutionTime;
124
122
  }
123
+ /**
124
+ * Returns the last result of the debounced function
125
+ */
126
+ getLastResult() {
127
+ return this._lastResult;
128
+ }
129
+ /**
130
+ * Returns the number of times the function has been executed successfully
131
+ */
132
+ getSuccessCount() {
133
+ return this._successCount;
134
+ }
135
+ /**
136
+ * Returns the number of times the function has settled (completed or errored)
137
+ */
138
+ getSettleCount() {
139
+ return this._settleCount;
140
+ }
141
+ /**
142
+ * Returns the number of times the function has errored
143
+ */
144
+ getErrorCount() {
145
+ return this._errorCount;
146
+ }
125
147
  /**
126
148
  * Returns the current pending state
127
149
  */
128
150
  getIsPending() {
129
- return this._isPending;
151
+ return this._options.enabled && !!this._timeoutId;
152
+ }
153
+ /**
154
+ * Returns the current executing state
155
+ */
156
+ getIsExecuting() {
157
+ return this._isExecuting;
130
158
  }
131
159
  }
132
160
  function asyncThrottle(fn, initialOptions) {
@@ -1 +1 @@
1
- {"version":3,"file":"async-throttler.cjs","sources":["../../src/async-throttler.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async throttled function\n */\nexport interface AsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Optional error handler for when the throttled function throws\n */\n onError?: (error: unknown) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onExecute?: (throttler: AsyncThrottler<TFn, TArgs>) => void\n /**\n * Time window in milliseconds during which the function can only be executed once\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<AsyncThrottlerOptions<any, any>> = {\n enabled: true,\n onError: () => {},\n onExecute: () => {},\n wait: 0,\n}\n\n/**\n * A class that creates an async throttled function.\n *\n * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.\n * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a\n * regular interval regardless of how often it's called.\n *\n * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to\n * ensure a maximum execution frequency.\n *\n * @example\n * ```ts\n * const throttler = new AsyncThrottler(async (value: string) => {\n * await saveToAPI(value);\n * }, { wait: 1000 });\n *\n * // Will only execute once per second no matter how often called\n * inputElement.addEventListener('input', () => {\n * throttler.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class AsyncThrottler<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n> {\n private _options: Required<AsyncThrottlerOptions<TFn, TArgs>>\n private _abortController: AbortController | null = null\n private _executionCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: TArgs | undefined\n private _lastExecutionTime = 0\n private _nextExecutionTime = 0\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn, TArgs>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the throttler options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<AsyncThrottlerOptions<TFn, TArgs>>,\n ): Required<AsyncThrottlerOptions<TFn, TArgs>> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n return this._options\n }\n\n /**\n * Returns the current options\n */\n getOptions(): Required<AsyncThrottlerOptions<TFn, TArgs>> {\n return this._options\n }\n\n /**\n * Attempts to execute the throttled function\n * If a call is already in progress, it may be blocked or queued depending on the `wait` option\n */\n async maybeExecute(...args: TArgs): Promise<void> {\n this._lastArgs = args\n if (this._isPending) return\n this._isPending = true\n\n this._abortController = new AbortController()\n const signal = this._abortController.signal\n\n try {\n while (this._isExecuting) {\n await this.delay(this._options.wait, signal)\n }\n\n while (Date.now() < this._nextExecutionTime) {\n await this.delay(this._nextExecutionTime - Date.now(), signal)\n }\n\n this._isPending = false\n this._isExecuting = true\n\n await this.executeFunction(...this._lastArgs)\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n return // Silent return on cancellation\n }\n try {\n this._options.onError(error)\n } catch {\n // Ignore errors from error handler\n }\n } finally {\n this._lastExecutionTime = Date.now()\n this._nextExecutionTime = this._lastExecutionTime + this._options.wait\n this._isExecuting = false\n this._abortController = null\n }\n }\n\n private delay(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(resolve, ms)\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timeout)\n reject(new Error('AbortError'))\n },\n { once: true },\n )\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 this._options.onExecute(this)\n }\n\n /**\n * Cancels any pending execution\n */\n cancel(): void {\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._isPending = false\n this._lastArgs = undefined\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns the last execution time\n */\n getLastExecutionTime(): number {\n return this._lastExecutionTime\n }\n\n /**\n * Returns the next execution time\n */\n getNextExecutionTime(): number {\n return this._nextExecutionTime\n }\n\n /**\n * Returns the current pending state\n */\n getIsPending(): boolean {\n return this._isPending\n }\n}\n\n/**\n * Creates an async throttled function that limits how often the function can execute.\n * The throttled function will execute at most once per wait period, even if called multiple times.\n * If called while executing, it will wait until execution completes before scheduling the next call.\n *\n * @example\n * ```ts\n * const throttled = asyncThrottle(async () => {\n * await someAsyncOperation();\n * }, { wait: 1000 });\n *\n * // This will execute at most once per second\n * await throttled();\n * await throttled(); // Waits 1 second before executing\n * ```\n */\nexport function asyncThrottle<\n TFn extends AnyAsyncFunction,\n TArgs extends Parameters<TFn>,\n>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions<TFn, TArgs>, 'enabled'>) {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n return asyncThrottler.maybeExecute.bind(asyncThrottler)\n}\n"],"names":[],"mappings":";;AA6BA,MAAM,iBAA4D;AAAA,EAChE,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AA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,KAAK,qBAAqB,KAAK,SAAS;AAClE,WAAK,eAAe;AACpB,WAAK,mBAAmB;AAAA,IAAA;AAAA,EAC1B;AAAA,EAGM,MAAM,IAAY,QAAoC;AAC5D,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AAChC,YAAA,UAAU,WAAW,SAAS,EAAE;AAC/B,aAAA;AAAA,QACL;AAAA,QACA,MAAM;AACJ,uBAAa,OAAO;AACb,iBAAA,IAAI,MAAM,YAAY,CAAC;AAAA,QAChC;AAAA,QACA,EAAE,MAAM,KAAK;AAAA,MACf;AAAA,IAAA,CACD;AAAA,EAAA;AAAA,EAGH,MAAc,mBAAmB,MAA4B;AACvD,QAAA,CAAC,KAAK,SAAS,QAAS;AACvB,SAAA;AACC,UAAA,KAAK,GAAG,GAAG,IAAI;AAChB,SAAA,SAAS,UAAU,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM9B,SAAe;AACb,QAAI,KAAK,kBAAkB;AACzB,WAAK,iBAAiB,MAAM;AAC5B,WAAK,mBAAmB;AAAA,IAAA;AAE1B,SAAK,aAAa;AAClB,SAAK,YAAY;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMnB,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAkBgB,SAAA,cAGd,IAAS,gBAAoE;AAC7E,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}
1
+ {"version":3,"file":"async-throttler.cjs","sources":["../../src/async-throttler.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async throttled function\n */\nexport interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute the function immediately when called\n * Defaults to true\n */\n leading?: boolean\n /**\n * Optional error handler for when the throttled function throws\n */\n onError?: (error: unknown, asyncThrottler: AsyncThrottler<TFn>) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onSettled?: (asyncThrottler: AsyncThrottler<TFn>) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n asyncThrottler: AsyncThrottler<TFn>,\n ) => void\n /**\n * Whether to execute the function on the trailing edge of the wait period\n * Defaults to true\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<AsyncThrottlerOptions<any>> = {\n enabled: true,\n leading: true,\n onError: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async throttled function.\n *\n * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.\n * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a\n * regular interval regardless of how often it's called.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to\n * ensure a maximum execution frequency.\n *\n * @example\n * ```ts\n * const throttler = new AsyncThrottler(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, { wait: 1000 });\n *\n * // Will only execute once per second no matter how often called\n * // Returns the API response directly\n * const result = await throttler.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncThrottler<TFn extends AnyAsyncFunction> {\n private _options: Required<AsyncThrottlerOptions<TFn>>\n private _abortController: AbortController | null = null\n private _errorCount = 0\n private _isExecuting = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastExecutionTime = 0\n private _lastResult: ReturnType<TFn> | undefined\n private _nextExecutionTime = 0\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the throttler options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this.cancel()\n }\n }\n\n /**\n * Returns the current options\n */\n getOptions(): Required<AsyncThrottlerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Attempts to execute the throttled function\n * If a call is already in progress, it may be blocked or queued depending on the `wait` option\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n const now = Date.now()\n const timeSinceLastExecution = now - this._lastExecutionTime\n\n // Handle leading execution\n if (this._options.leading && timeSinceLastExecution >= this._options.wait) {\n await this.executeFunction(...args)\n return this._lastResult\n } else {\n // Store the most recent arguments for potential trailing execution\n this._lastArgs = args\n\n return new Promise((resolve) => {\n // Clear any existing timeout to ensure we use the latest arguments\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n }\n\n // Set up trailing execution if enabled\n if (this._options.trailing) {\n const _timeSinceLastExecution = this._lastExecutionTime\n ? now - this._lastExecutionTime\n : 0\n const timeoutDuration = this._options.wait - _timeSinceLastExecution\n this._timeoutId = setTimeout(async () => {\n if (this._lastArgs !== undefined) {\n await this.executeFunction(...this._lastArgs)\n }\n resolve(this._lastResult)\n }, timeoutDuration)\n }\n })\n }\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled || this._isExecuting) 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._settleCount++\n this._abortController = null\n this._lastExecutionTime = Date.now()\n this._nextExecutionTime = this._lastExecutionTime + this._options.wait\n this._options.onSettled(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\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 }\n\n /**\n * Returns the last execution time\n */\n getLastExecutionTime(): number {\n return this._lastExecutionTime\n }\n\n /**\n * Returns the next execution time\n */\n getNextExecutionTime(): number {\n return this._nextExecutionTime\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 the current pending state\n */\n getIsPending(): boolean {\n return this._options.enabled && !!this._timeoutId\n }\n\n /**\n * Returns the current executing state\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n}\n\n/**\n * Creates an async throttled function that limits how often the function can execute.\n * The throttled function will execute at most once per wait period, even if called multiple times.\n * If called while executing, it will wait until execution completes before scheduling the next call.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * @example\n * ```ts\n * const throttled = asyncThrottle(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, { wait: 1000 });\n *\n * // This will execute at most once per second\n * // Returns the API response directly\n * const result = await throttled(inputElement.value);\n * ```\n */\nexport function asyncThrottle<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: Omit<AsyncThrottlerOptions<TFn>, 'enabled'>,\n) {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n return asyncThrottler.maybeExecute.bind(asyncThrottler)\n}\n"],"names":[],"mappings":";;AA2CA,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;AA4BO,MAAM,eAA6C;AAAA,EAaxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAZV,SAAQ,mBAA2C;AACnD,SAAQ,cAAc;AACtB,SAAQ,eAAe;AAEvB,SAAQ,qBAAqB;AAE7B,SAAQ,qBAAqB;AAC7B,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,OAAO;AAAA,IAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAMF,aAAmD;AACjD,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,MAAM,gBACD,MACmC;AAChC,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,yBAAyB,MAAM,KAAK;AAG1C,QAAI,KAAK,SAAS,WAAW,0BAA0B,KAAK,SAAS,MAAM;AACnE,YAAA,KAAK,gBAAgB,GAAG,I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AA;AAE1B,SAAK,YAAY;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMnB,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,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;AACtB,WAAO,KAAK,SAAS,WAAW,CAAC,CAAC,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMzC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAuBgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}
@@ -2,20 +2,34 @@ import { AnyAsyncFunction } from './types.cjs';
2
2
  /**
3
3
  * Options for configuring an async throttled function
4
4
  */
5
- export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>> {
5
+ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
6
6
  /**
7
7
  * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
8
8
  * Defaults to true.
9
9
  */
10
10
  enabled?: boolean;
11
+ /**
12
+ * Whether to execute the function immediately when called
13
+ * Defaults to true
14
+ */
15
+ leading?: boolean;
11
16
  /**
12
17
  * Optional error handler for when the throttled function throws
13
18
  */
14
- onError?: (error: unknown) => void;
19
+ onError?: (error: unknown, asyncThrottler: AsyncThrottler<TFn>) => void;
20
+ /**
21
+ * Optional function to call when the throttled function is executed
22
+ */
23
+ onSettled?: (asyncThrottler: AsyncThrottler<TFn>) => void;
15
24
  /**
16
25
  * Optional function to call when the throttled function is executed
17
26
  */
18
- onExecute?: (throttler: AsyncThrottler<TFn, TArgs>) => void;
27
+ onSuccess?: (result: ReturnType<TFn>, asyncThrottler: AsyncThrottler<TFn>) => void;
28
+ /**
29
+ * Whether to execute the function on the trailing edge of the wait period
30
+ * Defaults to true
31
+ */
32
+ trailing?: boolean;
19
33
  /**
20
34
  * Time window in milliseconds during which the function can only be executed once
21
35
  * Defaults to 0ms
@@ -29,56 +43,58 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction, TArgs exten
29
43
  * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
30
44
  * regular interval regardless of how often it's called.
31
45
  *
46
+ * Unlike the non-async Throttler, this async version supports returning values from the throttled function,
47
+ * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
48
+ * instead of setting the result on a state variable from within the throttled function.
49
+ *
32
50
  * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to
33
51
  * ensure a maximum execution frequency.
34
52
  *
35
53
  * @example
36
54
  * ```ts
37
55
  * const throttler = new AsyncThrottler(async (value: string) => {
38
- * await saveToAPI(value);
56
+ * const result = await saveToAPI(value);
57
+ * return result; // Return value is preserved
39
58
  * }, { wait: 1000 });
40
59
  *
41
60
  * // Will only execute once per second no matter how often called
42
- * inputElement.addEventListener('input', () => {
43
- * throttler.maybeExecute(inputElement.value);
44
- * });
61
+ * // Returns the API response directly
62
+ * const result = await throttler.maybeExecute(inputElement.value);
45
63
  * ```
46
64
  */
47
- export declare class AsyncThrottler<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>> {
65
+ export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
48
66
  private fn;
49
67
  private _options;
50
68
  private _abortController;
51
- private _executionCount;
69
+ private _errorCount;
52
70
  private _isExecuting;
53
- private _isPending;
54
71
  private _lastArgs;
55
72
  private _lastExecutionTime;
73
+ private _lastResult;
56
74
  private _nextExecutionTime;
57
- constructor(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn, TArgs>);
75
+ private _settleCount;
76
+ private _successCount;
77
+ private _timeoutId;
78
+ constructor(fn: TFn, initialOptions: AsyncThrottlerOptions<TFn>);
58
79
  /**
59
80
  * Updates the throttler options
60
81
  * Returns the new options state
61
82
  */
62
- setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn, TArgs>>): Required<AsyncThrottlerOptions<TFn, TArgs>>;
83
+ setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn>>): void;
63
84
  /**
64
85
  * Returns the current options
65
86
  */
66
- getOptions(): Required<AsyncThrottlerOptions<TFn, TArgs>>;
87
+ getOptions(): Required<AsyncThrottlerOptions<TFn>>;
67
88
  /**
68
89
  * Attempts to execute the throttled function
69
90
  * If a call is already in progress, it may be blocked or queued depending on the `wait` option
70
91
  */
71
- maybeExecute(...args: TArgs): Promise<void>;
72
- private delay;
92
+ maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
73
93
  private executeFunction;
74
94
  /**
75
- * Cancels any pending execution
95
+ * Cancels any pending execution or aborts any execution in progress
76
96
  */
77
97
  cancel(): void;
78
- /**
79
- * Returns the number of times the function has been executed
80
- */
81
- getExecutionCount(): number;
82
98
  /**
83
99
  * Returns the last execution time
84
100
  */
@@ -87,25 +103,50 @@ export declare class AsyncThrottler<TFn extends AnyAsyncFunction, TArgs extends
87
103
  * Returns the next execution time
88
104
  */
89
105
  getNextExecutionTime(): number;
106
+ /**
107
+ * Returns the last result of the debounced function
108
+ */
109
+ getLastResult(): ReturnType<TFn> | undefined;
110
+ /**
111
+ * Returns the number of times the function has been executed successfully
112
+ */
113
+ getSuccessCount(): number;
114
+ /**
115
+ * Returns the number of times the function has settled (completed or errored)
116
+ */
117
+ getSettleCount(): number;
118
+ /**
119
+ * Returns the number of times the function has errored
120
+ */
121
+ getErrorCount(): number;
90
122
  /**
91
123
  * Returns the current pending state
92
124
  */
93
125
  getIsPending(): boolean;
126
+ /**
127
+ * Returns the current executing state
128
+ */
129
+ getIsExecuting(): boolean;
94
130
  }
95
131
  /**
96
132
  * Creates an async throttled function that limits how often the function can execute.
97
133
  * The throttled function will execute at most once per wait period, even if called multiple times.
98
134
  * If called while executing, it will wait until execution completes before scheduling the next call.
99
135
  *
136
+ * Unlike the non-async Throttler, this async version supports returning values from the throttled function,
137
+ * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
138
+ * instead of setting the result on a state variable from within the throttled function.
139
+ *
100
140
  * @example
101
141
  * ```ts
102
- * const throttled = asyncThrottle(async () => {
103
- * await someAsyncOperation();
142
+ * const throttled = asyncThrottle(async (value: string) => {
143
+ * const result = await saveToAPI(value);
144
+ * return result; // Return value is preserved
104
145
  * }, { wait: 1000 });
105
146
  *
106
147
  * // This will execute at most once per second
107
- * await throttled();
108
- * await throttled(); // Waits 1 second before executing
148
+ * // Returns the API response directly
149
+ * const result = await throttled(inputElement.value);
109
150
  * ```
110
151
  */
111
- export declare function asyncThrottle<TFn extends AnyAsyncFunction, TArgs extends Parameters<TFn>>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions<TFn, TArgs>, 'enabled'>): (...args: TArgs) => Promise<void>;
152
+ export declare function asyncThrottle<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
@@ -3,17 +3,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const defaultOptions = {
4
4
  enabled: true,
5
5
  leading: false,
6
- trailing: true,
7
- wait: 0,
8
6
  onExecute: () => {
9
- }
7
+ },
8
+ trailing: true,
9
+ wait: 0
10
10
  };
11
11
  class Debouncer {
12
12
  constructor(fn, initialOptions) {
13
13
  this.fn = fn;
14
14
  this._canLeadingExecute = true;
15
- this._isPending = false;
16
15
  this._executionCount = 0;
16
+ this._isPending = false;
17
17
  this._options = {
18
18
  ...defaultOptions,
19
19
  ...initialOptions
@@ -24,14 +24,10 @@ class Debouncer {
24
24
  * Returns the new options state
25
25
  */
26
26
  setOptions(newOptions) {
27
- this._options = {
28
- ...this._options,
29
- ...newOptions
30
- };
27
+ this._options = { ...this._options, ...newOptions };
31
28
  if (!this._options.enabled) {
32
29
  this._isPending = false;
33
30
  }
34
- return this._options;
35
31
  }
36
32
  /**
37
33
  * Returns the current debouncer options
@@ -44,25 +40,27 @@ class Debouncer {
44
40
  * If a call is already in progress, it will be queued
45
41
  */
46
42
  maybeExecute(...args) {
43
+ let _didLeadingExecute = false;
47
44
  if (this._options.leading && this._canLeadingExecute) {
48
- this.executeFunction(...args);
49
45
  this._canLeadingExecute = false;
46
+ _didLeadingExecute = true;
47
+ this.executeFunction(...args);
50
48
  }
51
- if (this._options.leading || this._options.trailing) {
49
+ if (this._options.trailing) {
52
50
  this._isPending = true;
53
51
  }
54
52
  if (this._timeoutId) clearTimeout(this._timeoutId);
55
53
  this._timeoutId = setTimeout(() => {
56
54
  this._canLeadingExecute = true;
57
- this._isPending = false;
58
- if (this._options.trailing) {
55
+ if (this._options.trailing && !_didLeadingExecute) {
59
56
  this.executeFunction(...args);
60
57
  }
61
58
  }, this._options.wait);
62
59
  }
63
60
  executeFunction(...args) {
64
- if (!this._options.enabled) return;
61
+ if (!this._options.enabled) return void 0;
65
62
  this.fn(...args);
63
+ this._isPending = false;
66
64
  this._executionCount++;
67
65
  this._options.onExecute(this);
68
66
  }
@@ -1 +1 @@
1
- {"version":3,"file":"debouncer.cjs","sources":["../../src/debouncer.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<\n TFn extends AnyFunction,\n TArgs extends Parameters<TFn>,\n> {\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 * Callback function that is called after the function is executed\n */\n onExecute?: (debouncer: Debouncer<TFn, TArgs>) => 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 * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<DebouncerOptions<any, any>> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n onExecute: () => {},\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 *\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 * @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, TArgs extends Parameters<TFn>> {\n private _canLeadingExecute = true\n private _isPending = false\n private _executionCount = 0\n private _options: Required<DebouncerOptions<TFn, TArgs>>\n private _timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: DebouncerOptions<TFn, TArgs>,\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<DebouncerOptions<TFn, TArgs>>,\n ): Required<DebouncerOptions<TFn, TArgs>> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n\n return this._options\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<DebouncerOptions<TFn, TArgs>> {\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 maybeExecute(...args: TArgs): void {\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this.executeFunction(...args)\n this._canLeadingExecute = false\n }\n\n // Start pending state\n if (this._options.leading || this._options.trailing) {\n this._isPending = true\n }\n\n // Clear any existing timeout\n if (this._timeoutId) clearTimeout(this._timeoutId)\n\n // Set new timeout that will reset canLeadingExecute\n this._timeoutId = setTimeout(() => {\n this._canLeadingExecute = true\n this._isPending = false\n // Execute trailing only if enabled\n if (this._options.trailing) {\n this.executeFunction(...args)\n }\n }, this._options.wait)\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this._options.enabled) return\n this.fn(...args) // EXECUTE!\n this._executionCount++\n this._options.onExecute(this)\n }\n\n /**\n * Cancels any pending execution\n */\n cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._canLeadingExecute = true\n this._isPending = false\n }\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns `true` if debouncing\n */\n getIsPending(): boolean {\n return this._options.enabled && this._isPending\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 the the simple function wrapper implementation pulled from the Debouncer class. If you need\n * more control over the debouncing behavior, use the Debouncer class directly.\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 * @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: Omit<DebouncerOptions<TFn, Parameters<TFn>>, 'enabled'>,\n) {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute.bind(debouncer)\n}\n"],"names":[],"mappings":";;AAmCA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AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM9B,SAAe;AACb,QAAI,KAAK,YAAY;AACnB,mBAAa,KAAK,UAAU;AAC5B,WAAK,qBAAqB;AAC1B,WAAK,aAAa;AAAA,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAMF,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,SAAS,WAAW,KAAK;AAAA,EAAA;AAEzC;AAsBgB,SAAA,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;;;"}
1
+ {"version":3,"file":"debouncer.cjs","sources":["../../src/debouncer.ts"],"sourcesContent":["import type { AnyFunction } from './types'\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 * Defaults to true.\n */\n enabled?: boolean\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?: (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 * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<DebouncerOptions<any>> = {\n enabled: true,\n leading: false,\n onExecute: () => {},\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 *\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 * @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 private _canLeadingExecute = true\n private _executionCount = 0\n private _isPending = false\n private _options: Required<DebouncerOptions<TFn>>\n private _timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: DebouncerOptions<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<DebouncerOptions<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<DebouncerOptions<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 maybeExecute(...args: Parameters<TFn>): void {\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n _didLeadingExecute = true\n this.executeFunction(...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._isPending = true\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._canLeadingExecute = true\n if (this._options.trailing && !_didLeadingExecute) {\n this.executeFunction(...args)\n }\n }, this._options.wait)\n }\n\n private executeFunction(...args: Parameters<TFn>): void {\n if (!this._options.enabled) return undefined\n this.fn(...args) // EXECUTE!\n this._isPending = false\n this._executionCount++\n this._options.onExecute(this)\n }\n\n /**\n * Cancels any pending execution\n */\n cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._canLeadingExecute = true\n this._isPending = false\n }\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns `true` if debouncing\n */\n getIsPending(): boolean {\n return this._options.enabled && this._isPending\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 the the simple function wrapper implementation pulled from the Debouncer class. If you need\n * more control over the debouncing behavior, use the Debouncer class directly.\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 * @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: Omit<DebouncerOptions<TFn>, 'enabled'>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute.bind(debouncer)\n}\n"],"names":[],"mappings":";;AAiCA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AAyBO,MAAM,UAAmC;AAAA,EAO9C,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAQ,qBAAqB;AAC7B,SAAQ,kBAAkB;AAC1B,SAAQ,aAAa;AAQnB,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAkD;AAC3D,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAG9C,QAAA,CAAC,KAAK,SAAS,SAAS;AAC1B,WAAK,aAAa;AAAA,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAA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export interface DebouncerOptions<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
5
+ export interface DebouncerOptions<TFn extends AnyFunction> {
6
6
  /**
7
7
  * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
8
8
  * Defaults to true.
@@ -10,13 +10,14 @@ export interface DebouncerOptions<TFn extends AnyFunction, TArgs extends Paramet
10
10
  enabled?: boolean;
11
11
  /**
12
12
  * Whether to execute on the leading edge of the timeout.
13
+ * The first call will execute immediately and the rest will wait the delay.
13
14
  * Defaults to false.
14
15
  */
15
16
  leading?: boolean;
16
17
  /**
17
18
  * Callback function that is called after the function is executed
18
19
  */
19
- onExecute?: (debouncer: Debouncer<TFn, TArgs>) => void;
20
+ onExecute?: (debouncer: Debouncer<TFn>) => void;
20
21
  /**
21
22
  * Whether to execute on the trailing edge of the timeout.
22
23
  * Defaults to true.
@@ -51,28 +52,28 @@ export interface DebouncerOptions<TFn extends AnyFunction, TArgs extends Paramet
51
52
  * });
52
53
  * ```
53
54
  */
54
- export declare class Debouncer<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
55
+ export declare class Debouncer<TFn extends AnyFunction> {
55
56
  private fn;
56
57
  private _canLeadingExecute;
57
- private _isPending;
58
58
  private _executionCount;
59
+ private _isPending;
59
60
  private _options;
60
61
  private _timeoutId;
61
- constructor(fn: TFn, initialOptions: DebouncerOptions<TFn, TArgs>);
62
+ constructor(fn: TFn, initialOptions: DebouncerOptions<TFn>);
62
63
  /**
63
64
  * Updates the debouncer options
64
65
  * Returns the new options state
65
66
  */
66
- setOptions(newOptions: Partial<DebouncerOptions<TFn, TArgs>>): Required<DebouncerOptions<TFn, TArgs>>;
67
+ setOptions(newOptions: Partial<DebouncerOptions<TFn>>): void;
67
68
  /**
68
69
  * Returns the current debouncer options
69
70
  */
70
- getOptions(): Required<DebouncerOptions<TFn, TArgs>>;
71
+ getOptions(): Required<DebouncerOptions<TFn>>;
71
72
  /**
72
73
  * Attempts to execute the debounced function
73
74
  * If a call is already in progress, it will be queued
74
75
  */
75
- maybeExecute(...args: TArgs): void;
76
+ maybeExecute(...args: Parameters<TFn>): void;
76
77
  private executeFunction;
77
78
  /**
78
79
  * Cancels any pending execution
@@ -107,4 +108,4 @@ export declare class Debouncer<TFn extends AnyFunction, TArgs extends Parameters
107
108
  * inputElement.addEventListener('input', debounced);
108
109
  * ```
109
110
  */
110
- export declare function debounce<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<DebouncerOptions<TFn, Parameters<TFn>>, 'enabled'>): (...args: Parameters<TFn>) => void;
111
+ export declare function debounce<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<DebouncerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => void;