@tanstack/pacer 0.1.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 (72) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/async-debouncer.cjs +109 -0
  3. package/dist/cjs/async-debouncer.cjs.map +1 -0
  4. package/dist/cjs/async-debouncer.d.cts +99 -0
  5. package/dist/cjs/async-queuer.cjs +293 -0
  6. package/dist/cjs/async-queuer.cjs.map +1 -0
  7. package/dist/cjs/async-queuer.d.cts +197 -0
  8. package/dist/cjs/async-rate-limiter.cjs +122 -0
  9. package/dist/cjs/async-rate-limiter.cjs.map +1 -0
  10. package/dist/cjs/async-rate-limiter.d.cts +132 -0
  11. package/dist/cjs/async-throttler.cjs +115 -0
  12. package/dist/cjs/async-throttler.cjs.map +1 -0
  13. package/dist/cjs/async-throttler.d.cts +93 -0
  14. package/dist/cjs/compare.cjs +72 -0
  15. package/dist/cjs/compare.cjs.map +1 -0
  16. package/dist/cjs/compare.d.cts +12 -0
  17. package/dist/cjs/debouncer.cjs +74 -0
  18. package/dist/cjs/debouncer.cjs.map +1 -0
  19. package/dist/cjs/debouncer.d.cts +96 -0
  20. package/dist/cjs/index.cjs +32 -0
  21. package/dist/cjs/index.cjs.map +1 -0
  22. package/dist/cjs/index.d.cts +9 -0
  23. package/dist/cjs/queuer.cjs +231 -0
  24. package/dist/cjs/queuer.cjs.map +1 -0
  25. package/dist/cjs/queuer.d.cts +221 -0
  26. package/dist/cjs/rate-limiter.cjs +115 -0
  27. package/dist/cjs/rate-limiter.cjs.map +1 -0
  28. package/dist/cjs/rate-limiter.d.cts +147 -0
  29. package/dist/cjs/throttler.cjs +120 -0
  30. package/dist/cjs/throttler.cjs.map +1 -0
  31. package/dist/cjs/throttler.d.cts +139 -0
  32. package/dist/esm/async-debouncer.d.ts +99 -0
  33. package/dist/esm/async-debouncer.js +109 -0
  34. package/dist/esm/async-debouncer.js.map +1 -0
  35. package/dist/esm/async-queuer.d.ts +197 -0
  36. package/dist/esm/async-queuer.js +293 -0
  37. package/dist/esm/async-queuer.js.map +1 -0
  38. package/dist/esm/async-rate-limiter.d.ts +132 -0
  39. package/dist/esm/async-rate-limiter.js +122 -0
  40. package/dist/esm/async-rate-limiter.js.map +1 -0
  41. package/dist/esm/async-throttler.d.ts +93 -0
  42. package/dist/esm/async-throttler.js +115 -0
  43. package/dist/esm/async-throttler.js.map +1 -0
  44. package/dist/esm/compare.d.ts +12 -0
  45. package/dist/esm/compare.js +72 -0
  46. package/dist/esm/compare.js.map +1 -0
  47. package/dist/esm/debouncer.d.ts +96 -0
  48. package/dist/esm/debouncer.js +74 -0
  49. package/dist/esm/debouncer.js.map +1 -0
  50. package/dist/esm/index.d.ts +9 -0
  51. package/dist/esm/index.js +32 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/queuer.d.ts +221 -0
  54. package/dist/esm/queuer.js +231 -0
  55. package/dist/esm/queuer.js.map +1 -0
  56. package/dist/esm/rate-limiter.d.ts +147 -0
  57. package/dist/esm/rate-limiter.js +115 -0
  58. package/dist/esm/rate-limiter.js.map +1 -0
  59. package/dist/esm/throttler.d.ts +139 -0
  60. package/dist/esm/throttler.js +120 -0
  61. package/dist/esm/throttler.js.map +1 -0
  62. package/package.json +150 -0
  63. package/src/async-debouncer.ts +197 -0
  64. package/src/async-queuer.ts +447 -0
  65. package/src/async-rate-limiter.ts +228 -0
  66. package/src/async-throttler.ts +194 -0
  67. package/src/compare.ts +105 -0
  68. package/src/debouncer.ts +164 -0
  69. package/src/index.ts +9 -0
  70. package/src/queuer.ts +394 -0
  71. package/src/rate-limiter.ts +236 -0
  72. package/src/throttler.ts +222 -0
@@ -0,0 +1,115 @@
1
+ const defaultOptions = {
2
+ enabled: true,
3
+ limit: 1,
4
+ window: 0
5
+ };
6
+ class RateLimiter {
7
+ constructor(fn, initialOptions) {
8
+ this.fn = fn;
9
+ this.executionCount = 0;
10
+ this.rejectionCount = 0;
11
+ this.executionTimes = [];
12
+ this.options = {
13
+ ...defaultOptions,
14
+ ...initialOptions
15
+ };
16
+ }
17
+ /**
18
+ * Updates the rate limiter options
19
+ * Returns the new options state
20
+ */
21
+ setOptions(newOptions) {
22
+ this.options = {
23
+ ...this.options,
24
+ ...newOptions
25
+ };
26
+ return this.options;
27
+ }
28
+ /**
29
+ * Returns the number of times the function has been executed
30
+ */
31
+ getExecutionCount() {
32
+ return this.executionCount;
33
+ }
34
+ /**
35
+ * Returns the number of times the function has been rejected
36
+ */
37
+ getRejectionCount() {
38
+ return this.rejectionCount;
39
+ }
40
+ /**
41
+ * Returns the number of remaining executions allowed in the current window
42
+ */
43
+ getRemainingInWindow() {
44
+ this.cleanupOldExecutions();
45
+ return Math.max(0, this.options.limit - this.executionTimes.length);
46
+ }
47
+ /**
48
+ * Attempts to execute the rate-limited function if within the configured limits.
49
+ * Will reject execution if the number of calls in the current window exceeds the limit.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
54
+ *
55
+ * // First 5 calls will return true
56
+ * rateLimiter.maybeExecute('arg1', 'arg2'); // true
57
+ *
58
+ * // Additional calls within the window will return false
59
+ * rateLimiter.maybeExecute('arg1', 'arg2'); // false
60
+ * ```
61
+ */
62
+ maybeExecute(...args) {
63
+ this.cleanupOldExecutions();
64
+ if (this.executionTimes.length < this.options.limit) {
65
+ this.executeFunction(...args);
66
+ return true;
67
+ }
68
+ this.rejectFunction();
69
+ return false;
70
+ }
71
+ executeFunction(...args) {
72
+ if (!this.options.enabled) return;
73
+ const now = Date.now();
74
+ this.executionCount++;
75
+ this.executionTimes.push(now);
76
+ this.fn(...args);
77
+ }
78
+ rejectFunction() {
79
+ this.rejectionCount++;
80
+ if (this.options.onReject) {
81
+ const oldestExecution = Math.min(...this.executionTimes);
82
+ const msUntilNextWindow = oldestExecution + this.options.window - Date.now();
83
+ this.options.onReject({
84
+ msUntilNextWindow,
85
+ currentExecutions: this.executionTimes.length,
86
+ limit: this.options.limit,
87
+ rejectionCount: this.rejectionCount
88
+ });
89
+ }
90
+ }
91
+ cleanupOldExecutions() {
92
+ const now = Date.now();
93
+ const windowStart = now - this.options.window;
94
+ this.executionTimes = this.executionTimes.filter(
95
+ (time) => time > windowStart
96
+ );
97
+ }
98
+ /**
99
+ * Resets the rate limiter state
100
+ */
101
+ reset() {
102
+ this.executionTimes = [];
103
+ this.executionCount = 0;
104
+ this.rejectionCount = 0;
105
+ }
106
+ }
107
+ function rateLimit(fn, initialOptions) {
108
+ const rateLimiter = new RateLimiter(fn, initialOptions);
109
+ return rateLimiter.maybeExecute.bind(rateLimiter);
110
+ }
111
+ export {
112
+ RateLimiter,
113
+ rateLimit
114
+ };
115
+ //# sourceMappingURL=rate-limiter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limiter.js","sources":["../../src/rate-limiter.ts"],"sourcesContent":["/**\n * Information about a rate limit rejection\n */\nexport interface RateLimitRejectionInfo {\n /**\n * Number of milliseconds until the next execution will be possible\n */\n msUntilNextWindow: number\n /**\n * Current number of executions in the window\n */\n currentExecutions: number\n /**\n * Maximum allowed executions per window\n */\n limit: number\n /**\n * Total number of rejections that have occurred\n */\n rejectionCount: number\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions {\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 * Time window in milliseconds within which the limit applies\n */\n window: number\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (info: RateLimitRejectionInfo) => void\n}\n\nconst defaultOptions: Required<Omit<RateLimiterOptions, 'onReject'>> = {\n enabled: true,\n limit: 1,\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<\n TFn extends (...args: Array<any>) => any,\n TArgs extends Parameters<TFn>,\n> {\n private executionCount = 0\n private rejectionCount = 0\n private executionTimes: Array<number> = []\n private options: RateLimiterOptions\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions,\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>): RateLimiterOptions {\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 * 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 * 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: TArgs): 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: TArgs): void {\n if (!this.options.enabled) return\n const now = Date.now()\n this.executionCount++\n this.executionTimes.push(now)\n this.fn(...args)\n }\n\n private rejectFunction(): void {\n this.rejectionCount++\n if (this.options.onReject) {\n const oldestExecution = Math.min(...this.executionTimes)\n const msUntilNextWindow =\n oldestExecution + this.options.window - Date.now()\n\n this.options.onReject({\n msUntilNextWindow,\n currentExecutions: this.executionTimes.length,\n limit: this.options.limit,\n rejectionCount: this.rejectionCount,\n })\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 * 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: ({ msUntilNextWindow }) => {\n * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}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 (...args: Array<any>) => any>(\n fn: TFn,\n initialOptions: Omit<RateLimiterOptions, 'enabled'>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":"AA6CA,MAAM,iBAAiE;AAAA,EACrE,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AACV;AA2BO,MAAM,YAGX;AAAA,EAMA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,iBAAiB;AACzB,SAAQ,iBAAiB;AACzB,SAAQ,iBAAgC,CAAC;AAOvC,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAA6D;AACtE,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,SAAK,qBAAqB;AACnB,WAAA,KAAK,IAAI,GAAG,KAAK,QAAQ,QAAQ,KAAK,eAAe,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBpE,gBAAgB,MAAsB;AACpC,SAAK,qBAAqB;AAE1B,QAAI,KAAK,eAAe,SAAS,KAAK,QAAQ,OAAO;AAC9C,WAAA,gBAAgB,GAAG,IAAI;AACrB,aAAA;AAAA,IAAA;AAGT,SAAK,eAAe;AAEb,WAAA;AAAA,EAAA;AAAA,EAGD,mBAAmB,MAAmB;AACxC,QAAA,CAAC,KAAK,QAAQ,QAAS;AACrB,UAAA,MAAM,KAAK,IAAI;AAChB,SAAA;AACA,SAAA,eAAe,KAAK,GAAG;AACvB,SAAA,GAAG,GAAG,IAAI;AAAA,EAAA;AAAA,EAGT,iBAAuB;AACxB,SAAA;AACD,QAAA,KAAK,QAAQ,UAAU;AACzB,YAAM,kBAAkB,KAAK,IAAI,GAAG,KAAK,cAAc;AACvD,YAAM,oBACJ,kBAAkB,KAAK,QAAQ,SAAS,KAAK,IAAI;AAEnD,WAAK,QAAQ,SAAS;AAAA,QACpB;AAAA,QACA,mBAAmB,KAAK,eAAe;AAAA,QACvC,OAAO,KAAK,QAAQ;AAAA,QACpB,gBAAgB,KAAK;AAAA,MAAA,CACtB;AAAA,IAAA;AAAA,EACH;AAAA,EAGM,uBAA6B;AAC7B,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,cAAc,MAAM,KAAK,QAAQ;AAClC,SAAA,iBAAiB,KAAK,eAAe;AAAA,MACxC,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,QAAc;AACZ,SAAK,iBAAiB,CAAC;AACvB,SAAK,iBAAiB;AACtB,SAAK,iBAAiB;AAAA,EAAA;AAE1B;AAgCgB,SAAA,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AAC/C,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;"}
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Options for configuring a throttled function
3
+ */
4
+ export interface ThrottlerOptions {
5
+ /**
6
+ * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
7
+ * Defaults to true.
8
+ */
9
+ enabled?: boolean;
10
+ /**
11
+ * Whether to execute on the leading edge of the timeout.
12
+ * Defaults to true.
13
+ */
14
+ leading?: boolean;
15
+ /**
16
+ * Whether to execute on the trailing edge of the timeout.
17
+ * Defaults to true.
18
+ */
19
+ trailing?: boolean;
20
+ /**
21
+ * Time window in milliseconds during which the function can only be executed once
22
+ */
23
+ wait: number;
24
+ }
25
+ /**
26
+ * A class that creates a throttled function.
27
+ *
28
+ * Throttling ensures a function is called at most once within a specified time window.
29
+ * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
30
+ * execution timing regardless of call frequency.
31
+ *
32
+ * Supports both leading and trailing edge execution:
33
+ * - Leading: Execute immediately on first call (default: true)
34
+ * - Trailing: Execute after wait period if called during throttle (default: true)
35
+ *
36
+ * For rate limiting or hard API limits, consider using RateLimiter instead.
37
+ * For collapsing rapid-fire events, consider using Debouncer.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const throttler = new Throttler(
42
+ * (id: string) => api.getData(id),
43
+ * { wait: 1000 } // Execute at most once per second
44
+ * );
45
+ *
46
+ * // First call executes immediately
47
+ * throttler.maybeExecute('123');
48
+ *
49
+ * // Subsequent calls within 1000ms are throttled
50
+ * throttler.maybeExecute('123'); // Throttled
51
+ * ```
52
+ */
53
+ export declare class Throttler<TFn extends (...args: Array<any>) => any, TArgs extends Parameters<TFn>> {
54
+ private fn;
55
+ private executionCount;
56
+ private lastArgs;
57
+ private lastExecutionTime;
58
+ private options;
59
+ private timeoutId;
60
+ constructor(fn: TFn, initialOptions: ThrottlerOptions);
61
+ /**
62
+ * Updates the throttler options
63
+ * Returns the new options state
64
+ */
65
+ setOptions(newOptions: Partial<ThrottlerOptions>): Required<ThrottlerOptions>;
66
+ /**
67
+ * Returns the number of times the function has been executed
68
+ */
69
+ getExecutionCount(): number;
70
+ /**
71
+ * Returns the last execution time
72
+ */
73
+ getLastExecutionTime(): number;
74
+ /**
75
+ * Returns the next execution time
76
+ */
77
+ getNextExecutionTime(): number;
78
+ /**
79
+ * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
80
+ *
81
+ * - If enough time has passed since the last execution (>= wait period):
82
+ * - With leading=true: Executes immediately
83
+ * - With leading=false: Waits for the next trailing execution
84
+ *
85
+ * - If within the wait period:
86
+ * - With trailing=true: Schedules execution for end of wait period
87
+ * - With trailing=false: Drops the execution
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * const throttled = new Throttler(fn, { wait: 1000 });
92
+ *
93
+ * // First call executes immediately
94
+ * throttled.maybeExecute('a', 'b');
95
+ *
96
+ * // Call during wait period - gets throttled
97
+ * throttled.maybeExecute('c', 'd');
98
+ * ```
99
+ */
100
+ maybeExecute(...args: TArgs): void;
101
+ private executeFunction;
102
+ /**
103
+ * Cancels any pending trailing execution and clears internal state.
104
+ *
105
+ * If a trailing execution is scheduled (due to throttling with trailing=true),
106
+ * this will prevent that execution from occurring. The internal timeout and
107
+ * stored arguments will be cleared.
108
+ *
109
+ * Has no effect if there is no pending execution.
110
+ */
111
+ cancel(): void;
112
+ }
113
+ /**
114
+ * Creates a throttled function that limits how often the provided function can execute.
115
+ *
116
+ * Throttling ensures a function executes at most once within a specified time window,
117
+ * regardless of how many times it is called. This is useful for rate-limiting
118
+ * expensive operations or UI updates.
119
+ *
120
+ * The throttled function can be configured to execute on the leading and/or trailing
121
+ * edge of the throttle window via options.
122
+ *
123
+ * For handling bursts of events, consider using debounce() instead. For hard execution
124
+ * limits, consider using rateLimit().
125
+ *
126
+ * @example
127
+ * ```ts
128
+ * // Basic throttling - max once per second
129
+ * const throttled = throttle(updateUI, { wait: 1000 });
130
+ *
131
+ * // Configure leading/trailing execution
132
+ * const throttled = throttle(saveData, {
133
+ * wait: 2000,
134
+ * leading: true, // Execute immediately on first call
135
+ * trailing: true // Execute again after delay if called during wait
136
+ * });
137
+ * ```
138
+ */
139
+ export declare function throttle<TFn extends (...args: Array<any>) => any>(fn: TFn, initialOptions: Omit<ThrottlerOptions, 'enabled'>): (...args: Parameters<TFn>) => void;
@@ -0,0 +1,120 @@
1
+ const defaultOptions = {
2
+ enabled: true,
3
+ leading: true,
4
+ trailing: true,
5
+ wait: 0
6
+ };
7
+ class Throttler {
8
+ constructor(fn, initialOptions) {
9
+ this.fn = fn;
10
+ this.executionCount = 0;
11
+ this.lastExecutionTime = 0;
12
+ this.options = {
13
+ ...defaultOptions,
14
+ ...initialOptions
15
+ };
16
+ }
17
+ /**
18
+ * Updates the throttler options
19
+ * Returns the new options state
20
+ */
21
+ setOptions(newOptions) {
22
+ this.options = {
23
+ ...this.options,
24
+ ...newOptions
25
+ };
26
+ return this.options;
27
+ }
28
+ /**
29
+ * Returns the number of times the function has been executed
30
+ */
31
+ getExecutionCount() {
32
+ return this.executionCount;
33
+ }
34
+ /**
35
+ * Returns the last execution time
36
+ */
37
+ getLastExecutionTime() {
38
+ return this.lastExecutionTime;
39
+ }
40
+ /**
41
+ * Returns the next execution time
42
+ */
43
+ getNextExecutionTime() {
44
+ return this.lastExecutionTime + this.options.wait;
45
+ }
46
+ /**
47
+ * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
48
+ *
49
+ * - If enough time has passed since the last execution (>= wait period):
50
+ * - With leading=true: Executes immediately
51
+ * - With leading=false: Waits for the next trailing execution
52
+ *
53
+ * - If within the wait period:
54
+ * - With trailing=true: Schedules execution for end of wait period
55
+ * - With trailing=false: Drops the execution
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const throttled = new Throttler(fn, { wait: 1000 });
60
+ *
61
+ * // First call executes immediately
62
+ * throttled.maybeExecute('a', 'b');
63
+ *
64
+ * // Call during wait period - gets throttled
65
+ * throttled.maybeExecute('c', 'd');
66
+ * ```
67
+ */
68
+ maybeExecute(...args) {
69
+ const now = Date.now();
70
+ const timeSinceLastExecution = now - this.lastExecutionTime;
71
+ if (timeSinceLastExecution >= this.options.wait) {
72
+ if (this.options.leading) {
73
+ this.executeFunction(...args);
74
+ }
75
+ this.lastExecutionTime = now;
76
+ } else {
77
+ this.lastArgs = args;
78
+ if (!this.timeoutId && this.options.trailing) {
79
+ this.timeoutId = setTimeout(() => {
80
+ if (this.lastArgs) {
81
+ this.executeFunction(...this.lastArgs);
82
+ this.lastArgs = void 0;
83
+ }
84
+ this.lastExecutionTime = Date.now();
85
+ this.timeoutId = void 0;
86
+ }, this.options.wait - timeSinceLastExecution);
87
+ }
88
+ }
89
+ }
90
+ executeFunction(...args) {
91
+ if (!this.options.enabled) return;
92
+ this.executionCount++;
93
+ this.fn(...args);
94
+ }
95
+ /**
96
+ * Cancels any pending trailing execution and clears internal state.
97
+ *
98
+ * If a trailing execution is scheduled (due to throttling with trailing=true),
99
+ * this will prevent that execution from occurring. The internal timeout and
100
+ * stored arguments will be cleared.
101
+ *
102
+ * Has no effect if there is no pending execution.
103
+ */
104
+ cancel() {
105
+ if (this.timeoutId) {
106
+ clearTimeout(this.timeoutId);
107
+ this.timeoutId = void 0;
108
+ this.lastArgs = void 0;
109
+ }
110
+ }
111
+ }
112
+ function throttle(fn, initialOptions) {
113
+ const throttler = new Throttler(fn, initialOptions);
114
+ return throttler.maybeExecute.bind(throttler);
115
+ }
116
+ export {
117
+ Throttler,
118
+ throttle
119
+ };
120
+ //# sourceMappingURL=throttler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throttler.js","sources":["../../src/throttler.ts"],"sourcesContent":["/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions {\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 on the leading edge of the timeout.\n * Defaults to true.\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 * Time window in milliseconds during which the function can only be executed once\n */\n wait: number\n}\n\nconst defaultOptions: Required<ThrottlerOptions> = {\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For rate limiting or hard API limits, consider using RateLimiter instead.\n * For collapsing rapid-fire events, consider using Debouncer.\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<\n TFn extends (...args: Array<any>) => any,\n TArgs extends Parameters<TFn>,\n> {\n private executionCount = 0\n private lastArgs: TArgs | undefined\n private lastExecutionTime = 0\n private options: Required<ThrottlerOptions>\n private timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: ThrottlerOptions,\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<ThrottlerOptions>,\n ): Required<ThrottlerOptions> {\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 * 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.lastExecutionTime + this.options.wait\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute(...args: TArgs): void {\n const now = Date.now()\n const timeSinceLastExecution = now - this.lastExecutionTime\n\n // Handle leading execution\n if (timeSinceLastExecution >= this.options.wait) {\n if (this.options.leading) {\n this.executeFunction(...args)\n }\n this.lastExecutionTime = now\n } else {\n // Store the most recent arguments for potential trailing execution\n this.lastArgs = args\n\n // Set up trailing execution if not already scheduled\n if (!this.timeoutId && this.options.trailing) {\n this.timeoutId = setTimeout(() => {\n if (this.lastArgs) {\n this.executeFunction(...this.lastArgs)\n this.lastArgs = undefined\n }\n this.lastExecutionTime = Date.now()\n this.timeoutId = undefined\n }, this.options.wait - timeSinceLastExecution)\n }\n }\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this.options.enabled) return\n this.executionCount++\n this.fn(...args)\n }\n\n /**\n * Cancels any pending trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel(): void {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = undefined\n this.lastArgs = undefined\n }\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * @example\n * ```ts\n * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends (...args: Array<any>) => any>(\n fn: TFn,\n initialOptions: Omit<ThrottlerOptions, 'enabled'>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute.bind(throttler)\n}\n"],"names":[],"mappings":"AAyBA,MAAM,iBAA6C;AAAA,EACjD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AA8BO,MAAM,UAGX;AAAA,EAOA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAQ,iBAAiB;AAEzB,SAAQ,oBAAoB;AAQ1B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YAC4B;AAC5B,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,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;AACtB,WAAA,KAAK,oBAAoB,KAAK,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAyB/C,gBAAgB,MAAmB;AAC3B,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,yBAAyB,MAAM,KAAK;AAGtC,QAAA,0BAA0B,KAAK,QAAQ,MAAM;AAC3C,UAAA,KAAK,QAAQ,SAAS;AACnB,aAAA,gBAAgB,GAAG,IAAI;AAAA,MAAA;AAE9B,WAAK,oBAAoB;AAAA,IAAA,OACpB;AAEL,WAAK,WAAW;AAGhB,UAAI,CAAC,KAAK,aAAa,KAAK,QAAQ,UAAU;AACvC,aAAA,YAAY,WAAW,MAAM;AAChC,cAAI,KAAK,UAAU;AACZ,iBAAA,gBAAgB,GAAG,KAAK,QAAQ;AACrC,iBAAK,WAAW;AAAA,UAAA;AAEb,eAAA,oBAAoB,KAAK,IAAI;AAClC,eAAK,YAAY;AAAA,QAChB,GAAA,KAAK,QAAQ,OAAO,sBAAsB;AAAA,MAAA;AAAA,IAC/C;AAAA,EACF;AAAA,EAGM,mBAAmB,MAAmB;AACxC,QAAA,CAAC,KAAK,QAAQ,QAAS;AACtB,SAAA;AACA,SAAA,GAAG,GAAG,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYjB,SAAe;AACb,QAAI,KAAK,WAAW;AAClB,mBAAa,KAAK,SAAS;AAC3B,WAAK,YAAY;AACjB,WAAK,WAAW;AAAA,IAAA;AAAA,EAClB;AAEJ;AA4BgB,SAAA,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;"}
package/package.json ADDED
@@ -0,0 +1,150 @@
1
+ {
2
+ "name": "@tanstack/pacer",
3
+ "version": "0.1.0",
4
+ "description": "Utilities for debouncing, throttling, rate-limiting, queuing, and more.",
5
+ "author": "Tanner Linsley",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/TanStack/pacer.git",
10
+ "directory": "packages/pacer"
11
+ },
12
+ "homepage": "https://tanstack.com/pacer",
13
+ "funding": {
14
+ "type": "github",
15
+ "url": "https://github.com/sponsors/tannerlinsley"
16
+ },
17
+ "keywords": [
18
+ "debounce",
19
+ "throttle",
20
+ "rate-limit",
21
+ "queuer",
22
+ "queue",
23
+ "pacer"
24
+ ],
25
+ "type": "module",
26
+ "types": "dist/esm/index.d.ts",
27
+ "main": "dist/cjs/index.cjs",
28
+ "module": "dist/esm/index.js",
29
+ "exports": {
30
+ ".": {
31
+ "import": {
32
+ "types": "./dist/esm/index.d.ts",
33
+ "default": "./dist/esm/index.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/cjs/index.d.cts",
37
+ "default": "./dist/cjs/index.cjs"
38
+ }
39
+ },
40
+ "./async-debouncer": {
41
+ "import": {
42
+ "types": "./dist/esm/async-debouncer.d.ts",
43
+ "default": "./dist/esm/async-debouncer.js"
44
+ },
45
+ "require": {
46
+ "types": "./dist/cjs/async-debouncer.d.cts",
47
+ "default": "./dist/cjs/async-debouncer.cjs"
48
+ }
49
+ },
50
+ "./async-queuer": {
51
+ "import": {
52
+ "types": "./dist/esm/async-queuer.d.ts",
53
+ "default": "./dist/esm/async-queuer.js"
54
+ },
55
+ "require": {
56
+ "types": "./dist/cjs/async-queuer.d.cts",
57
+ "default": "./dist/cjs/async-queuer.cjs"
58
+ }
59
+ },
60
+ "./async-rate-limiter": {
61
+ "import": {
62
+ "types": "./dist/esm/async-rate-limiter.d.ts",
63
+ "default": "./dist/esm/async-rate-limiter.js"
64
+ },
65
+ "require": {
66
+ "types": "./dist/cjs/async-rate-limiter.d.cts",
67
+ "default": "./dist/cjs/async-rate-limiter.cjs"
68
+ }
69
+ },
70
+ "./async-throttler": {
71
+ "import": {
72
+ "types": "./dist/esm/async-throttler.d.ts",
73
+ "default": "./dist/esm/async-throttler.js"
74
+ },
75
+ "require": {
76
+ "types": "./dist/cjs/async-throttler.d.cts",
77
+ "default": "./dist/cjs/async-throttler.cjs"
78
+ }
79
+ },
80
+ "./compare": {
81
+ "import": {
82
+ "types": "./dist/esm/compare.d.ts",
83
+ "default": "./dist/esm/compare.js"
84
+ },
85
+ "require": {
86
+ "types": "./dist/cjs/compare.d.cts",
87
+ "default": "./dist/cjs/compare.cjs"
88
+ }
89
+ },
90
+ "./debouncer": {
91
+ "import": {
92
+ "types": "./dist/esm/debouncer.d.ts",
93
+ "default": "./dist/esm/debouncer.js"
94
+ },
95
+ "require": {
96
+ "types": "./dist/cjs/debouncer.d.cts",
97
+ "default": "./dist/cjs/debouncer.cjs"
98
+ }
99
+ },
100
+ "./queuer": {
101
+ "import": {
102
+ "types": "./dist/esm/queuer.d.ts",
103
+ "default": "./dist/esm/queuer.js"
104
+ },
105
+ "require": {
106
+ "types": "./dist/cjs/queuer.d.cts",
107
+ "default": "./dist/cjs/queuer.cjs"
108
+ }
109
+ },
110
+ "./rate-limiter": {
111
+ "import": {
112
+ "types": "./dist/esm/rate-limiter.d.ts",
113
+ "default": "./dist/esm/rate-limiter.js"
114
+ },
115
+ "require": {
116
+ "types": "./dist/cjs/rate-limiter.d.cts",
117
+ "default": "./dist/cjs/rate-limiter.cjs"
118
+ }
119
+ },
120
+ "./throttler": {
121
+ "import": {
122
+ "types": "./dist/esm/throttler.d.ts",
123
+ "default": "./dist/esm/throttler.js"
124
+ },
125
+ "require": {
126
+ "types": "./dist/cjs/throttler.d.cts",
127
+ "default": "./dist/cjs/throttler.cjs"
128
+ }
129
+ },
130
+ "./package.json": "./package.json"
131
+ },
132
+ "sideEffects": false,
133
+ "engines": {
134
+ "node": ">=18"
135
+ },
136
+ "files": [
137
+ "dist/",
138
+ "src"
139
+ ],
140
+ "scripts": {
141
+ "clean": "premove ./build ./dist",
142
+ "lint:fix": "eslint ./src --fix",
143
+ "test:eslint": "eslint ./src",
144
+ "test:lib": "vitest",
145
+ "test:lib:dev": "pnpm test:lib --watch",
146
+ "test:types": "tsc",
147
+ "test:build": "publint --strict",
148
+ "build": "vite build"
149
+ }
150
+ }