@tanstack/pacer 0.3.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.
@@ -5,7 +5,8 @@ const defaultOptions = {
5
5
  },
6
6
  onReject: () => {
7
7
  },
8
- window: 0
8
+ window: 0,
9
+ windowType: "fixed"
9
10
  };
10
11
  class RateLimiter {
11
12
  constructor(fn, initialOptions) {
@@ -48,9 +49,19 @@ class RateLimiter {
48
49
  */
49
50
  maybeExecute(...args) {
50
51
  this.cleanupOldExecutions();
51
- if (this._executionTimes.length < this._options.limit) {
52
- this.executeFunction(...args);
53
- return true;
52
+ if (this._options.windowType === "sliding") {
53
+ if (this._executionTimes.length < this._options.limit) {
54
+ this.executeFunction(...args);
55
+ return true;
56
+ }
57
+ } else {
58
+ const now = Date.now();
59
+ const oldestExecution = Math.min(...this._executionTimes);
60
+ const isNewWindow = oldestExecution + this._options.window <= now;
61
+ if (isNewWindow || this._executionTimes.length < this._options.limit) {
62
+ this.executeFunction(...args);
63
+ return true;
64
+ }
54
65
  }
55
66
  this.rejectFunction();
56
67
  return false;
@@ -100,6 +111,9 @@ class RateLimiter {
100
111
  * Returns the number of milliseconds until the next execution will be possible
101
112
  */
102
113
  getMsUntilNextWindow() {
114
+ if (this.getRemainingInWindow() > 0) {
115
+ return 0;
116
+ }
103
117
  const oldestExecution = Math.min(...this._executionTimes);
104
118
  return oldestExecution + this._options.window - Date.now();
105
119
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limiter.js","sources":["../../src/rate-limiter.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n}\n\nconst defaultOptions: Required<RateLimiterOptions<any>> = {\n enabled: true,\n limit: 1,\n onExecute: () => {},\n onReject: () => {},\n window: 0,\n}\n\n/**\n * A class that creates a rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n private _executionCount = 0\n private _rejectionCount = 0\n private _executionTimes: Array<number> = []\n private _options: RateLimiterOptions<TFn>\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<RateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<RateLimiterOptions<TFn>> {\n return this._options as Required<RateLimiterOptions<TFn>>\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute(...args: Parameters<TFn>): boolean {\n this.cleanupOldExecutions()\n\n if (this._executionTimes.length < this._options.limit) {\n this.executeFunction(...args)\n return true\n }\n\n this.rejectFunction()\n\n return false\n }\n\n private executeFunction(...args: Parameters<TFn>): void {\n if (!this._options.enabled) return\n const now = Date.now()\n this._executionCount++\n this._executionTimes.push(now)\n this.fn(...args) // execute the function\n this._options.onExecute?.(this)\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this._options.window\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\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 the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this._options.limit - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow(): number {\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this._options.window - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._executionCount = 0\n this._rejectionCount = 0\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: Omit<RateLimiterOptions<TFn>, 'enabled'>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":"AA6BA,MAAM,iBAAoD;AAAA,EACxD,SAAS;AAAA,EACT,OAAO;AAAA,EACP,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,QAAQ;AACV;AA2BO,MAAM,YAAqC;AAAA,EAMhD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAiC,CAAC;AAOxC,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAoD;AAC7D,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMpD,aAAgD;AAC9C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBd,gBAAgB,MAAgC;AAC9C,SAAK,qBAAqB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CgB,SAAA,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AAC/C,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;"}
1
+ {"version":3,"file":"rate-limiter.js","sources":["../../src/rate-limiter.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Required<RateLimiterOptions<any>> = {\n enabled: true,\n limit: 1,\n onExecute: () => {},\n onReject: () => {},\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n private _executionCount = 0\n private _rejectionCount = 0\n private _executionTimes: Array<number> = []\n private _options: RateLimiterOptions<TFn>\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<RateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<RateLimiterOptions<TFn>> {\n return this._options as Required<RateLimiterOptions<TFn>>\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute(...args: Parameters<TFn>): boolean {\n this.cleanupOldExecutions()\n\n if (this._options.windowType === 'sliding') {\n // For sliding window, we can execute if we have capacity in the current window\n if (this._executionTimes.length < this._options.limit) {\n this.executeFunction(...args)\n return true\n }\n } else {\n // For fixed window, we need to check if we're in a new window\n const now = Date.now()\n const oldestExecution = Math.min(...this._executionTimes)\n const isNewWindow = oldestExecution + this._options.window <= now\n\n if (isNewWindow || this._executionTimes.length < this._options.limit) {\n this.executeFunction(...args)\n return true\n }\n }\n\n this.rejectFunction()\n return false\n }\n\n private executeFunction(...args: Parameters<TFn>): void {\n if (!this._options.enabled) return\n const now = Date.now()\n this._executionCount++\n this._executionTimes.push(now)\n this.fn(...args) // execute the function\n this._options.onExecute?.(this)\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this._options.window\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\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 the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this._options.limit - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow(): number {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this._options.window - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._executionCount = 0\n this._rejectionCount = 0\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: Omit<RateLimiterOptions<TFn>, 'enabled'>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":"AAoCA,MAAM,iBAAoD;AAAA,EACxD,SAAS;AAAA,EACT,OAAO;AAAA,EACP,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,QAAQ;AAAA,EACR,YAAY;AACd;AAiCO,MAAM,YAAqC;AAAA,EAMhD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAiC,CAAC;AAOxC,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAoD;AAC7D,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMpD,aAAgD;AAC9C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBd,gBAAgB,MAAgC;AAC9C,SAAK,qBAAqB;AAEtB,QAAA,KAAK,SAAS,eAAe,WAAW;AAE1C,UAAI,KAAK,gBAAgB,SAAS,KAAK,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,qBAAqB,IAAI,GAAG;AAC5B,aAAA;AAAA,IAAA;AAET,UAAM,kBAAkB,KAAK,IAAI,GAAG,KAAK,eAAe;AACxD,WAAO,kBAAkB,KAAK,SAAS,SAAS,KAAK,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM3D,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,kBAAkB;AACvB,SAAK,kBAAkB;AAAA,EAAA;AAE3B;AAuCgB,SAAA,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AAC/C,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/pacer",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Utilities for debouncing, throttling, rate-limiting, queuing, and more.",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -58,16 +58,20 @@ const defaultOptions: Required<AsyncDebouncerOptions<any>> = {
58
58
  * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
59
59
  * the function stops being called for the specified delay period.
60
60
  *
61
+ * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,
62
+ * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
63
+ * instead of setting the result on a state variable from within the debounced function.
64
+ *
61
65
  * @example
62
66
  * ```ts
63
67
  * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
64
- * await searchAPI(value);
68
+ * const results = await searchAPI(value);
69
+ * return results; // Return value is preserved
65
70
  * }, { wait: 500 });
66
71
  *
67
72
  * // Called on each keystroke but only executes after 500ms of no typing
68
- * inputElement.addEventListener('input', () => {
69
- * asyncDebouncer.maybeExecute(inputElement.value);
70
- * });
73
+ * // Returns the API response directly
74
+ * const results = await asyncDebouncer.maybeExecute(inputElement.value);
71
75
  * ```
72
76
  */
73
77
  export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
@@ -245,16 +249,20 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
245
249
  * The debounced function will only execute once the wait period has elapsed without any new calls.
246
250
  * If called again during the wait period, the timer resets and a new wait period begins.
247
251
  *
252
+ * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,
253
+ * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
254
+ * instead of setting the result on a state variable from within the debounced function.
255
+ *
248
256
  * @example
249
257
  * ```ts
250
258
  * const debounced = asyncDebounce(async (value: string) => {
251
- * await saveToAPI(value);
259
+ * const result = await saveToAPI(value);
260
+ * return result; // Return value is preserved
252
261
  * }, { wait: 1000 });
253
262
  *
254
263
  * // Will only execute once, 1 second after the last call
255
- * await debounced("first"); // Cancelled
256
- * await debounced("second"); // Cancelled
257
- * await debounced("third"); // Executes after 1s
264
+ * // Returns the API response directly
265
+ * const result = await debounced("third");
258
266
  * ```
259
267
  */
260
268
  export function asyncDebounce<TFn extends AnyAsyncFunction>(
@@ -17,6 +17,10 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
17
17
  * Optional error handler for when the rate-limited function throws
18
18
  */
19
19
  onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void
20
+ /**
21
+ * Optional callback function that is called when an execution is rejected due to rate limiting
22
+ */
23
+ onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void
20
24
  /**
21
25
  * Optional function to call when the rate-limited function is executed
22
26
  */
@@ -28,14 +32,17 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
28
32
  result: ReturnType<TFn>,
29
33
  rateLimiter: AsyncRateLimiter<TFn>,
30
34
  ) => void
31
- /**
32
- * Optional callback function that is called when an execution is rejected due to rate limiting
33
- */
34
- onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void
35
35
  /**
36
36
  * Time window in milliseconds within which the limit applies
37
37
  */
38
38
  window: number
39
+ /**
40
+ * Type of window to use for rate limiting
41
+ * - 'fixed': Uses a fixed window that resets after the window period
42
+ * - 'sliding': Uses a sliding window that allows executions as old ones expire
43
+ * Defaults to 'fixed'
44
+ */
45
+ windowType?: 'fixed' | 'sliding'
39
46
  }
40
47
 
41
48
  const defaultOptions: Required<
@@ -46,6 +53,7 @@ const defaultOptions: Required<
46
53
  onReject: () => {},
47
54
  onSettled: () => {},
48
55
  onSuccess: () => {},
56
+ windowType: 'fixed',
49
57
  }
50
58
 
51
59
  /**
@@ -55,6 +63,16 @@ const defaultOptions: Required<
55
63
  * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
56
64
  * all executions happen immediately, followed by a complete block.
57
65
  *
66
+ * The rate limiter supports two types of windows:
67
+ * - 'fixed': A strict window that resets after the window period. All executions within the window count
68
+ * towards the limit, and the window resets completely after the period.
69
+ * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
70
+ * consistent rate of execution over time.
71
+ *
72
+ * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,
73
+ * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
74
+ * instead of setting the result on a state variable from within the rate-limited function.
75
+ *
58
76
  * For smoother execution patterns, consider using:
59
77
  * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
60
78
  * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
@@ -66,11 +84,12 @@ const defaultOptions: Required<
66
84
  * ```ts
67
85
  * const rateLimiter = new AsyncRateLimiter(
68
86
  * async (id: string) => await api.getData(id),
69
- * { limit: 5, window: 1000 } // 5 calls per second
87
+ * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window
70
88
  * );
71
89
  *
72
90
  * // Will execute immediately until limit reached, then block
73
- * await rateLimiter.maybeExecute('123');
91
+ * // Returns the API response directly
92
+ * const data = await rateLimiter.maybeExecute('123');
74
93
  * ```
75
94
  */
76
95
  export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
@@ -81,6 +100,7 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
81
100
  private _rejectionCount = 0
82
101
  private _settleCount = 0
83
102
  private _successCount = 0
103
+ private _isExecuting = false
84
104
 
85
105
  constructor(
86
106
  private fn: TFn,
@@ -128,9 +148,22 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
128
148
  ): Promise<ReturnType<TFn> | undefined> {
129
149
  this.cleanupOldExecutions()
130
150
 
131
- if (this._executionTimes.length < this._options.limit) {
132
- await this.executeFunction(...args)
133
- return this._lastResult
151
+ if (this._options.windowType === 'sliding') {
152
+ // For sliding window, we can execute if we have capacity in the current window
153
+ if (this._executionTimes.length < this._options.limit) {
154
+ await this.executeFunction(...args)
155
+ return this._lastResult
156
+ }
157
+ } else {
158
+ // For fixed window, we need to check if we're in a new window
159
+ const now = Date.now()
160
+ const oldestExecution = Math.min(...this._executionTimes)
161
+ const isNewWindow = oldestExecution + this._options.window <= now
162
+
163
+ if (isNewWindow || this._executionTimes.length < this._options.limit) {
164
+ await this.executeFunction(...args)
165
+ return this._lastResult
166
+ }
134
167
  }
135
168
 
136
169
  this.rejectFunction()
@@ -141,6 +174,7 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
141
174
  ...args: Parameters<TFn>
142
175
  ): Promise<ReturnType<TFn> | undefined> {
143
176
  if (!this._options.enabled) return
177
+ this._isExecuting = true
144
178
  const now = Date.now()
145
179
  this._executionTimes.push(now)
146
180
 
@@ -152,6 +186,7 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
152
186
  this._errorCount++
153
187
  this._options.onError?.(error, this)
154
188
  } finally {
189
+ this._isExecuting = false
155
190
  this._settleCount++
156
191
  this._options.onSettled?.(this)
157
192
  }
@@ -184,9 +219,15 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
184
219
 
185
220
  /**
186
221
  * Returns the number of milliseconds until the next execution will be possible
222
+ * For fixed windows, this is the time until the current window resets
223
+ * For sliding windows, this is the time until the oldest execution expires
187
224
  */
188
225
  getMsUntilNextWindow(): number {
189
- return this.getRemainingInWindow() * this._options.window
226
+ if (this.getRemainingInWindow() > 0) {
227
+ return 0
228
+ }
229
+ const oldestExecution = Math.min(...this._executionTimes)
230
+ return oldestExecution + this._options.window - Date.now()
190
231
  }
191
232
 
192
233
  /**
@@ -217,6 +258,13 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
217
258
  return this._rejectionCount
218
259
  }
219
260
 
261
+ /**
262
+ * Returns whether the function is currently executing
263
+ */
264
+ getIsExecuting(): boolean {
265
+ return this._isExecuting
266
+ }
267
+
220
268
  /**
221
269
  * Resets the rate limiter state
222
270
  */
@@ -232,6 +280,16 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
232
280
  /**
233
281
  * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.
234
282
  *
283
+ * Unlike the non-async rate limiter, this async version supports returning values from the rate-limited function,
284
+ * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
285
+ * instead of setting the result on a state variable from within the rate-limited function.
286
+ *
287
+ * The rate limiter supports two types of windows:
288
+ * - 'fixed': A strict window that resets after the window period. All executions within the window count
289
+ * towards the limit, and the window resets completely after the period.
290
+ * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
291
+ * consistent rate of execution over time.
292
+ *
235
293
  * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
236
294
  * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
237
295
  * - A throttler ensures even spacing between executions, which can be better for consistent performance
@@ -242,10 +300,11 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
242
300
  *
243
301
  * @example
244
302
  * ```ts
245
- * // Rate limit to 5 calls per minute
303
+ * // Rate limit to 5 calls per minute with a sliding window
246
304
  * const rateLimited = asyncRateLimit(makeApiCall, {
247
305
  * limit: 5,
248
306
  * window: 60000,
307
+ * windowType: 'sliding',
249
308
  * onReject: (rateLimiter) => {
250
309
  * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
251
310
  * }
@@ -253,7 +312,8 @@ export class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
253
312
  *
254
313
  * // First 5 calls will execute immediately
255
314
  * // Additional calls will be rejected until the minute window resets
256
- * await rateLimited();
315
+ * // Returns the API response directly
316
+ * const result = await rateLimited();
257
317
  *
258
318
  * // For more even execution, consider using throttle instead:
259
319
  * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
@@ -58,19 +58,23 @@ const defaultOptions: Required<AsyncThrottlerOptions<any>> = {
58
58
  * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
59
59
  * regular interval regardless of how often it's called.
60
60
  *
61
+ * Unlike the non-async Throttler, this async version supports returning values from the throttled function,
62
+ * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
63
+ * instead of setting the result on a state variable from within the throttled function.
64
+ *
61
65
  * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to
62
66
  * ensure a maximum execution frequency.
63
67
  *
64
68
  * @example
65
69
  * ```ts
66
70
  * const throttler = new AsyncThrottler(async (value: string) => {
67
- * await saveToAPI(value);
71
+ * const result = await saveToAPI(value);
72
+ * return result; // Return value is preserved
68
73
  * }, { wait: 1000 });
69
74
  *
70
75
  * // Will only execute once per second no matter how often called
71
- * inputElement.addEventListener('input', () => {
72
- * throttler.maybeExecute(inputElement.value);
73
- * });
76
+ * // Returns the API response directly
77
+ * const result = await throttler.maybeExecute(inputElement.value);
74
78
  * ```
75
79
  */
76
80
  export class AsyncThrottler<TFn extends AnyAsyncFunction> {
@@ -258,15 +262,20 @@ export class AsyncThrottler<TFn extends AnyAsyncFunction> {
258
262
  * The throttled function will execute at most once per wait period, even if called multiple times.
259
263
  * If called while executing, it will wait until execution completes before scheduling the next call.
260
264
  *
265
+ * Unlike the non-async Throttler, this async version supports returning values from the throttled function,
266
+ * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
267
+ * instead of setting the result on a state variable from within the throttled function.
268
+ *
261
269
  * @example
262
270
  * ```ts
263
- * const throttled = asyncThrottle(async () => {
264
- * await someAsyncOperation();
271
+ * const throttled = asyncThrottle(async (value: string) => {
272
+ * const result = await saveToAPI(value);
273
+ * return result; // Return value is preserved
265
274
  * }, { wait: 1000 });
266
275
  *
267
276
  * // This will execute at most once per second
268
- * await throttled();
269
- * await throttled(); // Waits 1 second before executing
277
+ * // Returns the API response directly
278
+ * const result = await throttled(inputElement.value);
270
279
  * ```
271
280
  */
272
281
  export function asyncThrottle<TFn extends AnyAsyncFunction>(
@@ -25,6 +25,13 @@ export interface RateLimiterOptions<TFn extends AnyFunction> {
25
25
  * Time window in milliseconds within which the limit applies
26
26
  */
27
27
  window: number
28
+ /**
29
+ * Type of window to use for rate limiting
30
+ * - 'fixed': Uses a fixed window that resets after the window period
31
+ * - 'sliding': Uses a sliding window that allows executions as old ones expire
32
+ * Defaults to 'fixed'
33
+ */
34
+ windowType?: 'fixed' | 'sliding'
28
35
  }
29
36
 
30
37
  const defaultOptions: Required<RateLimiterOptions<any>> = {
@@ -33,6 +40,7 @@ const defaultOptions: Required<RateLimiterOptions<any>> = {
33
40
  onExecute: () => {},
34
41
  onReject: () => {},
35
42
  window: 0,
43
+ windowType: 'fixed',
36
44
  }
37
45
 
38
46
  /**
@@ -42,6 +50,12 @@ const defaultOptions: Required<RateLimiterOptions<any>> = {
42
50
  * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
43
51
  * all executions happen immediately, followed by a complete block.
44
52
  *
53
+ * The rate limiter supports two types of windows:
54
+ * - 'fixed': A strict window that resets after the window period. All executions within the window count
55
+ * towards the limit, and the window resets completely after the period.
56
+ * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
57
+ * consistent rate of execution over time.
58
+ *
45
59
  * For smoother execution patterns, consider using:
46
60
  * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
47
61
  * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
@@ -53,7 +67,7 @@ const defaultOptions: Required<RateLimiterOptions<any>> = {
53
67
  * ```ts
54
68
  * const rateLimiter = new RateLimiter(
55
69
  * (id: string) => api.getData(id),
56
- * { limit: 5, window: 1000 } // 5 calls per second
70
+ * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window
57
71
  * );
58
72
  *
59
73
  * // Will execute immediately until limit reached, then block
@@ -109,13 +123,25 @@ export class RateLimiter<TFn extends AnyFunction> {
109
123
  maybeExecute(...args: Parameters<TFn>): boolean {
110
124
  this.cleanupOldExecutions()
111
125
 
112
- if (this._executionTimes.length < this._options.limit) {
113
- this.executeFunction(...args)
114
- return true
126
+ if (this._options.windowType === 'sliding') {
127
+ // For sliding window, we can execute if we have capacity in the current window
128
+ if (this._executionTimes.length < this._options.limit) {
129
+ this.executeFunction(...args)
130
+ return true
131
+ }
132
+ } else {
133
+ // For fixed window, we need to check if we're in a new window
134
+ const now = Date.now()
135
+ const oldestExecution = Math.min(...this._executionTimes)
136
+ const isNewWindow = oldestExecution + this._options.window <= now
137
+
138
+ if (isNewWindow || this._executionTimes.length < this._options.limit) {
139
+ this.executeFunction(...args)
140
+ return true
141
+ }
115
142
  }
116
143
 
117
144
  this.rejectFunction()
118
-
119
145
  return false
120
146
  }
121
147
 
@@ -169,6 +195,9 @@ export class RateLimiter<TFn extends AnyFunction> {
169
195
  * Returns the number of milliseconds until the next execution will be possible
170
196
  */
171
197
  getMsUntilNextWindow(): number {
198
+ if (this.getRemainingInWindow() > 0) {
199
+ return 0
200
+ }
172
201
  const oldestExecution = Math.min(...this._executionTimes)
173
202
  return oldestExecution + this._options.window - Date.now()
174
203
  }
@@ -191,15 +220,22 @@ export class RateLimiter<TFn extends AnyFunction> {
191
220
  * - A throttler ensures even spacing between executions, which can be better for consistent performance
192
221
  * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
193
222
  *
223
+ * The rate limiter supports two types of windows:
224
+ * - 'fixed': A strict window that resets after the window period. All executions within the window count
225
+ * towards the limit, and the window resets completely after the period.
226
+ * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
227
+ * consistent rate of execution over time.
228
+ *
194
229
  * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
195
230
  * need to enforce a hard limit on the number of executions within a time period.
196
231
  *
197
232
  * @example
198
233
  * ```ts
199
- * // Rate limit to 5 calls per minute
234
+ * // Rate limit to 5 calls per minute with a sliding window
200
235
  * const rateLimited = rateLimit(makeApiCall, {
201
236
  * limit: 5,
202
237
  * window: 60000,
238
+ * windowType: 'sliding',
203
239
  * onReject: (rateLimiter) => {
204
240
  * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
205
241
  * }