@tanstack/pacer 0.21.1 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -6
- package/dist/async-batcher.d.ts +11 -14
- package/dist/async-batcher.js +186 -132
- package/dist/async-debouncer.d.ts +10 -13
- package/dist/async-debouncer.js +187 -146
- package/dist/async-queuer.d.ts +12 -14
- package/dist/async-queuer.js +384 -259
- package/dist/async-rate-limiter.d.ts +9 -12
- package/dist/async-rate-limiter.js +198 -147
- package/dist/async-retryer.d.ts +10 -10
- package/dist/async-retryer.js +209 -188
- package/dist/async-throttler.d.ts +10 -13
- package/dist/async-throttler.js +215 -161
- package/dist/batcher.d.ts +5 -8
- package/dist/batcher.js +107 -87
- package/dist/debouncer.d.ts +6 -9
- package/dist/debouncer.js +99 -86
- package/dist/event-client.d.ts +8 -11
- package/dist/event-client.js +1 -2
- package/dist/index.js +1 -1
- package/dist/queuer.d.ts +8 -10
- package/dist/queuer.js +277 -207
- package/dist/rate-limiter.d.ts +6 -9
- package/dist/rate-limiter.js +127 -109
- package/dist/throttler.d.ts +6 -9
- package/dist/throttler.js +127 -90
- package/dist/types.d.ts +4 -6
- package/dist/utils.d.ts +3 -6
- package/dist/utils.js +1 -2
- package/package.json +23 -70
- package/dist/async-batcher.cjs +0 -337
- package/dist/async-batcher.cjs.map +0 -1
- package/dist/async-batcher.d.cts +0 -344
- package/dist/async-batcher.js.map +0 -1
- package/dist/async-debouncer.cjs +0 -330
- package/dist/async-debouncer.cjs.map +0 -1
- package/dist/async-debouncer.d.cts +0 -300
- package/dist/async-debouncer.js.map +0 -1
- package/dist/async-queuer.cjs +0 -484
- package/dist/async-queuer.cjs.map +0 -1
- package/dist/async-queuer.d.cts +0 -440
- package/dist/async-queuer.js.map +0 -1
- package/dist/async-rate-limiter.cjs +0 -373
- package/dist/async-rate-limiter.cjs.map +0 -1
- package/dist/async-rate-limiter.d.cts +0 -357
- package/dist/async-rate-limiter.js.map +0 -1
- package/dist/async-retryer.cjs +0 -374
- package/dist/async-retryer.cjs.map +0 -1
- package/dist/async-retryer.d.cts +0 -319
- package/dist/async-retryer.js.map +0 -1
- package/dist/async-throttler.cjs +0 -347
- package/dist/async-throttler.cjs.map +0 -1
- package/dist/async-throttler.d.cts +0 -320
- package/dist/async-throttler.js.map +0 -1
- package/dist/batcher.cjs +0 -200
- package/dist/batcher.cjs.map +0 -1
- package/dist/batcher.d.cts +0 -180
- package/dist/batcher.js.map +0 -1
- package/dist/debouncer.cjs +0 -203
- package/dist/debouncer.cjs.map +0 -1
- package/dist/debouncer.d.cts +0 -167
- package/dist/debouncer.js.map +0 -1
- package/dist/event-client.cjs +0 -64
- package/dist/event-client.cjs.map +0 -1
- package/dist/event-client.d.cts +0 -66
- package/dist/event-client.js.map +0 -1
- package/dist/index.cjs +0 -52
- package/dist/index.d.cts +0 -15
- package/dist/queuer.cjs +0 -401
- package/dist/queuer.cjs.map +0 -1
- package/dist/queuer.d.cts +0 -345
- package/dist/queuer.js.map +0 -1
- package/dist/rate-limiter.cjs +0 -263
- package/dist/rate-limiter.cjs.map +0 -1
- package/dist/rate-limiter.d.cts +0 -215
- package/dist/rate-limiter.js.map +0 -1
- package/dist/throttler.cjs +0 -215
- package/dist/throttler.cjs.map +0 -1
- package/dist/throttler.d.cts +0 -207
- package/dist/throttler.js.map +0 -1
- package/dist/types.cjs +0 -0
- package/dist/types.d.cts +0 -13
- package/dist/utils.cjs +0 -14
- package/dist/utils.cjs.map +0 -1
- package/dist/utils.d.cts +0 -8
- package/dist/utils.js.map +0 -1
- package/src/async-batcher.ts +0 -594
- package/src/async-debouncer.ts +0 -565
- package/src/async-queuer.ts +0 -925
- package/src/async-rate-limiter.ts +0 -647
- package/src/async-retryer.ts +0 -684
- package/src/async-throttler.ts +0 -633
- package/src/batcher.ts +0 -329
- package/src/debouncer.ts +0 -334
- package/src/event-client.ts +0 -129
- package/src/index.ts +0 -24
- package/src/queuer.ts +0 -740
- package/src/rate-limiter.ts +0 -429
- package/src/throttler.ts +0 -380
- package/src/types.ts +0 -12
- package/src/utils.ts +0 -12
package/dist/throttler.cjs
DELETED
|
@@ -1,215 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_utils = require('./utils.cjs');
|
|
3
|
-
const require_event_client = require('./event-client.cjs');
|
|
4
|
-
let _tanstack_store = require("@tanstack/store");
|
|
5
|
-
|
|
6
|
-
//#region src/throttler.ts
|
|
7
|
-
function getDefaultThrottlerState() {
|
|
8
|
-
return {
|
|
9
|
-
executionCount: 0,
|
|
10
|
-
isPending: false,
|
|
11
|
-
lastArgs: void 0,
|
|
12
|
-
lastExecutionTime: 0,
|
|
13
|
-
nextExecutionTime: 0,
|
|
14
|
-
status: "idle",
|
|
15
|
-
maybeExecuteCount: 0
|
|
16
|
-
};
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.
|
|
20
|
-
*/
|
|
21
|
-
function throttlerOptions(options) {
|
|
22
|
-
return options;
|
|
23
|
-
}
|
|
24
|
-
const defaultOptions = {
|
|
25
|
-
enabled: true,
|
|
26
|
-
leading: true,
|
|
27
|
-
trailing: true,
|
|
28
|
-
wait: 0
|
|
29
|
-
};
|
|
30
|
-
/**
|
|
31
|
-
* A class that creates a throttled function.
|
|
32
|
-
*
|
|
33
|
-
* Throttling ensures a function is called at most once within a specified time window.
|
|
34
|
-
* Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
|
|
35
|
-
* execution timing regardless of call frequency.
|
|
36
|
-
* This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
|
|
37
|
-
*
|
|
38
|
-
* Supports both leading and trailing edge execution:
|
|
39
|
-
* - Leading: Execute immediately on first call (default: true)
|
|
40
|
-
* - Trailing: Execute after wait period if called during throttle (default: true)
|
|
41
|
-
*
|
|
42
|
-
* For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
|
|
43
|
-
*
|
|
44
|
-
* State Management:
|
|
45
|
-
* - Uses TanStack Store for reactive state management
|
|
46
|
-
* - Use `initialState` to provide initial state values when creating the throttler
|
|
47
|
-
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
48
|
-
* - The state includes execution count, last execution time, pending status, and more
|
|
49
|
-
* - State can be accessed via `throttler.store.state` when using the class directly
|
|
50
|
-
* - When using framework adapters (React/Solid), state is accessed from `throttler.state`
|
|
51
|
-
*
|
|
52
|
-
* @example
|
|
53
|
-
* ```ts
|
|
54
|
-
* const throttler = new Throttler(
|
|
55
|
-
* (id: string) => api.getData(id),
|
|
56
|
-
* { wait: 1000 } // Execute at most once per second
|
|
57
|
-
* );
|
|
58
|
-
*
|
|
59
|
-
* // First call executes immediately
|
|
60
|
-
* throttler.maybeExecute('123');
|
|
61
|
-
*
|
|
62
|
-
* // Subsequent calls within 1000ms are throttled
|
|
63
|
-
* throttler.maybeExecute('123'); // Throttled
|
|
64
|
-
* ```
|
|
65
|
-
*/
|
|
66
|
-
var Throttler = class {
|
|
67
|
-
#timeoutId;
|
|
68
|
-
constructor(fn, initialOptions) {
|
|
69
|
-
this.fn = fn;
|
|
70
|
-
this.store = new _tanstack_store.Store(getDefaultThrottlerState());
|
|
71
|
-
this.setOptions = (newOptions) => {
|
|
72
|
-
this.options = {
|
|
73
|
-
...this.options,
|
|
74
|
-
...newOptions
|
|
75
|
-
};
|
|
76
|
-
if (!this.#getEnabled()) this.cancel();
|
|
77
|
-
};
|
|
78
|
-
this.#setState = (newState) => {
|
|
79
|
-
this.store.setState((state) => {
|
|
80
|
-
const combinedState = {
|
|
81
|
-
...state,
|
|
82
|
-
...newState
|
|
83
|
-
};
|
|
84
|
-
const { isPending } = combinedState;
|
|
85
|
-
return {
|
|
86
|
-
...combinedState,
|
|
87
|
-
status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
|
|
88
|
-
};
|
|
89
|
-
});
|
|
90
|
-
require_event_client.emitChange("Throttler", this);
|
|
91
|
-
};
|
|
92
|
-
this.#getEnabled = () => {
|
|
93
|
-
return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
|
|
94
|
-
};
|
|
95
|
-
this.#getWait = () => {
|
|
96
|
-
return require_utils.parseFunctionOrValue(this.options.wait, this);
|
|
97
|
-
};
|
|
98
|
-
this.maybeExecute = (...args) => {
|
|
99
|
-
this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
|
|
100
|
-
const now = Date.now();
|
|
101
|
-
const timeSinceLastExecution = now - this.store.state.lastExecutionTime;
|
|
102
|
-
const wait = this.#getWait();
|
|
103
|
-
if (this.options.leading && timeSinceLastExecution >= wait) this.#execute(...args);
|
|
104
|
-
else {
|
|
105
|
-
this.#setState({ lastArgs: args });
|
|
106
|
-
if (!this.#timeoutId && this.options.trailing) {
|
|
107
|
-
const timeoutDuration = wait - (this.store.state.lastExecutionTime ? now - this.store.state.lastExecutionTime : 0);
|
|
108
|
-
this.#setState({ isPending: true });
|
|
109
|
-
this.#timeoutId = setTimeout(() => {
|
|
110
|
-
const { lastArgs } = this.store.state;
|
|
111
|
-
if (lastArgs !== void 0) this.#execute(...lastArgs);
|
|
112
|
-
}, timeoutDuration);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
this.#execute = (...args) => {
|
|
117
|
-
if (!this.#getEnabled()) return;
|
|
118
|
-
this.fn(...args);
|
|
119
|
-
const lastExecutionTime = Date.now();
|
|
120
|
-
const nextExecutionTime = lastExecutionTime + this.#getWait();
|
|
121
|
-
this.#clearTimeout();
|
|
122
|
-
this.#setState({
|
|
123
|
-
executionCount: this.store.state.executionCount + 1,
|
|
124
|
-
lastExecutionTime,
|
|
125
|
-
nextExecutionTime,
|
|
126
|
-
isPending: false,
|
|
127
|
-
lastArgs: void 0
|
|
128
|
-
});
|
|
129
|
-
this.options.onExecute?.(args, this);
|
|
130
|
-
setTimeout(() => {
|
|
131
|
-
if (!this.store.state.isPending) this.#setState({ nextExecutionTime: void 0 });
|
|
132
|
-
}, this.#getWait());
|
|
133
|
-
};
|
|
134
|
-
this.flush = () => {
|
|
135
|
-
if (this.store.state.isPending && this.store.state.lastArgs) this.#execute(...this.store.state.lastArgs);
|
|
136
|
-
};
|
|
137
|
-
this.#clearTimeout = () => {
|
|
138
|
-
if (this.#timeoutId) {
|
|
139
|
-
clearTimeout(this.#timeoutId);
|
|
140
|
-
this.#timeoutId = void 0;
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
this.cancel = () => {
|
|
144
|
-
this.#clearTimeout();
|
|
145
|
-
this.#setState({
|
|
146
|
-
lastArgs: void 0,
|
|
147
|
-
isPending: false
|
|
148
|
-
});
|
|
149
|
-
};
|
|
150
|
-
this.reset = () => {
|
|
151
|
-
this.#setState(getDefaultThrottlerState());
|
|
152
|
-
};
|
|
153
|
-
this.key = initialOptions.key;
|
|
154
|
-
this.options = {
|
|
155
|
-
...defaultOptions,
|
|
156
|
-
...initialOptions
|
|
157
|
-
};
|
|
158
|
-
this.#setState(this.options.initialState ?? {});
|
|
159
|
-
if (this.key) require_event_client.pacerEventClient.on("d-Throttler", (event) => {
|
|
160
|
-
if (event.payload.key !== this.key) return;
|
|
161
|
-
this.#setState(event.payload.store.state);
|
|
162
|
-
this.setOptions(event.payload.options);
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
#setState;
|
|
166
|
-
#getEnabled;
|
|
167
|
-
#getWait;
|
|
168
|
-
#execute;
|
|
169
|
-
#clearTimeout;
|
|
170
|
-
};
|
|
171
|
-
/**
|
|
172
|
-
* Creates a throttled function that limits how often the provided function can execute.
|
|
173
|
-
*
|
|
174
|
-
* This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
|
|
175
|
-
*
|
|
176
|
-
* Throttling ensures a function executes at most once within a specified time window,
|
|
177
|
-
* regardless of how many times it is called. This is useful for rate-limiting
|
|
178
|
-
* expensive operations or UI updates.
|
|
179
|
-
*
|
|
180
|
-
* The throttled function can be configured to execute on the leading and/or trailing
|
|
181
|
-
* edge of the throttle window via options.
|
|
182
|
-
*
|
|
183
|
-
* For handling bursts of events, consider using debounce() instead. For hard execution
|
|
184
|
-
* limits, consider using rateLimit().
|
|
185
|
-
*
|
|
186
|
-
* State Management:
|
|
187
|
-
* - Uses TanStack Store for reactive state management
|
|
188
|
-
* - Use `initialState` to provide initial state values when creating the throttler
|
|
189
|
-
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
190
|
-
* - The state includes execution count, last execution time, pending status, and more
|
|
191
|
-
* - State can be accessed via the underlying Throttler instance's `store.state` property
|
|
192
|
-
* - When using framework adapters (React/Solid), state is accessed from the hook's state property
|
|
193
|
-
*
|
|
194
|
-
* @example
|
|
195
|
-
* ```ts
|
|
196
|
-
* // Basic throttling - max once per second
|
|
197
|
-
* const throttled = throttle(updateUI, { wait: 1000 });
|
|
198
|
-
*
|
|
199
|
-
* // Configure leading/trailing execution
|
|
200
|
-
* const throttled = throttle(saveData, {
|
|
201
|
-
* wait: 2000,
|
|
202
|
-
* leading: true, // Execute immediately on first call
|
|
203
|
-
* trailing: true // Execute again after delay if called during wait
|
|
204
|
-
* });
|
|
205
|
-
* ```
|
|
206
|
-
*/
|
|
207
|
-
function throttle(fn, initialOptions) {
|
|
208
|
-
return new Throttler(fn, initialOptions).maybeExecute;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
//#endregion
|
|
212
|
-
exports.Throttler = Throttler;
|
|
213
|
-
exports.throttle = throttle;
|
|
214
|
-
exports.throttlerOptions = throttlerOptions;
|
|
215
|
-
//# sourceMappingURL=throttler.cjs.map
|
package/dist/throttler.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"throttler.cjs","names":["Store","#getEnabled","parseFunctionOrValue","#setState","#getWait","#execute","#timeoutId","#clearTimeout"],"sources":["../src/throttler.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface ThrottlerState<TFn extends AnyFunction> {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the throttler is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Timestamp of the last function execution in milliseconds\n */\n lastExecutionTime: number\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number | undefined\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultThrottlerState<\n TFn extends AnyFunction,\n>(): ThrottlerState<TFn> {\n return {\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n nextExecutionTime: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Initial state for the throttler\n */\n initialState?: Partial<ThrottlerState<TFn>>\n /**\n * A key to identify the throttler.\n * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void\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 * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.\n */\nexport function throttlerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<\n ThrottlerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\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 * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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 collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via `throttler.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `throttler.state`\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<TFn extends AnyFunction> {\n readonly store: Store<Readonly<ThrottlerState<TFn>>> = new Store(\n getDefaultThrottlerState<TFn>(),\n )\n key: string | undefined\n options: ThrottlerOptions<TFn>\n #timeoutId: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Throttler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<ThrottlerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<ThrottlerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the throttler options\n */\n setOptions = (newOptions: Partial<ThrottlerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the throttler is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<ThrottlerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\n emitChange('Throttler', this)\n }\n\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\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: Parameters<TFn>): void => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n const now = Date.now()\n const timeSinceLastExecution = now - this.store.state.lastExecutionTime\n const wait = this.#getWait()\n\n // Handle leading execution\n if (this.options.leading && timeSinceLastExecution >= wait) {\n this.#execute(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this.#setState({\n lastArgs: args,\n })\n // Set up trailing execution if not already scheduled\n if (!this.#timeoutId && this.options.trailing) {\n // prevent large number if lastExecutionTime is undefined\n const _timeSinceLastExecution = this.store.state.lastExecutionTime\n ? now - this.store.state.lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this.#setState({ isPending: true })\n this.#timeoutId = setTimeout(() => {\n const { lastArgs } = this.store.state\n if (lastArgs !== undefined) {\n this.#execute(...lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n this.fn(...args) // EXECUTE!\n const lastExecutionTime = Date.now()\n const nextExecutionTime = lastExecutionTime + this.#getWait()\n this.#clearTimeout()\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n lastExecutionTime,\n nextExecutionTime,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n setTimeout(() => {\n if (!this.store.state.isPending) {\n this.#setState({ nextExecutionTime: undefined })\n }\n }, this.#getWait())\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#execute(...this.store.state.lastArgs)\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending 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 this.#clearTimeout()\n this.#setState({\n lastArgs: undefined,\n isPending: false,\n })\n }\n\n /**\n * Resets the throttler state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultThrottlerState<TFn>())\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via the underlying Throttler instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * // 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 AnyFunction>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute\n}\n"],"mappings":"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"}
|
package/dist/throttler.d.cts
DELETED
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
import { AnyFunction } from "./types.cjs";
|
|
2
|
-
import { Store } from "@tanstack/store";
|
|
3
|
-
|
|
4
|
-
//#region src/throttler.d.ts
|
|
5
|
-
interface ThrottlerState<TFn extends AnyFunction> {
|
|
6
|
-
/**
|
|
7
|
-
* Number of function executions that have been completed
|
|
8
|
-
*/
|
|
9
|
-
executionCount: number;
|
|
10
|
-
/**
|
|
11
|
-
* Whether the throttler is waiting for the timeout to trigger execution
|
|
12
|
-
*/
|
|
13
|
-
isPending: boolean;
|
|
14
|
-
/**
|
|
15
|
-
* The arguments from the most recent call to maybeExecute
|
|
16
|
-
*/
|
|
17
|
-
lastArgs: Parameters<TFn> | undefined;
|
|
18
|
-
/**
|
|
19
|
-
* Timestamp of the last function execution in milliseconds
|
|
20
|
-
*/
|
|
21
|
-
lastExecutionTime: number;
|
|
22
|
-
/**
|
|
23
|
-
* Number of times maybeExecute has been called (for reduction calculations)
|
|
24
|
-
*/
|
|
25
|
-
maybeExecuteCount: number;
|
|
26
|
-
/**
|
|
27
|
-
* Timestamp when the next execution can occur in milliseconds
|
|
28
|
-
*/
|
|
29
|
-
nextExecutionTime: number | undefined;
|
|
30
|
-
/**
|
|
31
|
-
* Current execution status - 'idle' when not active, 'pending' when waiting for timeout
|
|
32
|
-
*/
|
|
33
|
-
status: 'disabled' | 'idle' | 'pending';
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Options for configuring a throttled function
|
|
37
|
-
*/
|
|
38
|
-
interface ThrottlerOptions<TFn extends AnyFunction> {
|
|
39
|
-
/**
|
|
40
|
-
* Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
41
|
-
* Can be a boolean or a function that returns a boolean.
|
|
42
|
-
* Defaults to true.
|
|
43
|
-
*/
|
|
44
|
-
enabled?: boolean | ((throttler: Throttler<TFn>) => boolean);
|
|
45
|
-
/**
|
|
46
|
-
* Initial state for the throttler
|
|
47
|
-
*/
|
|
48
|
-
initialState?: Partial<ThrottlerState<TFn>>;
|
|
49
|
-
/**
|
|
50
|
-
* A key to identify the throttler.
|
|
51
|
-
* If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.
|
|
52
|
-
*/
|
|
53
|
-
key?: string;
|
|
54
|
-
/**
|
|
55
|
-
* Whether to execute on the leading edge of the timeout.
|
|
56
|
-
* Defaults to true.
|
|
57
|
-
*/
|
|
58
|
-
leading?: boolean;
|
|
59
|
-
/**
|
|
60
|
-
* Callback function that is called after the function is executed
|
|
61
|
-
*/
|
|
62
|
-
onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void;
|
|
63
|
-
/**
|
|
64
|
-
* Whether to execute on the trailing edge of the timeout.
|
|
65
|
-
* Defaults to true.
|
|
66
|
-
*/
|
|
67
|
-
trailing?: boolean;
|
|
68
|
-
/**
|
|
69
|
-
* Time window in milliseconds during which the function can only be executed once.
|
|
70
|
-
* Can be a number or a function that returns a number.
|
|
71
|
-
* Defaults to 0ms
|
|
72
|
-
*/
|
|
73
|
-
wait: number | ((throttler: Throttler<TFn>) => number);
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.
|
|
77
|
-
*/
|
|
78
|
-
declare function throttlerOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<ThrottlerOptions<TFn>>>(options: TOptions): TOptions;
|
|
79
|
-
/**
|
|
80
|
-
* A class that creates a throttled function.
|
|
81
|
-
*
|
|
82
|
-
* Throttling ensures a function is called at most once within a specified time window.
|
|
83
|
-
* Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
|
|
84
|
-
* execution timing regardless of call frequency.
|
|
85
|
-
* This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
|
|
86
|
-
*
|
|
87
|
-
* Supports both leading and trailing edge execution:
|
|
88
|
-
* - Leading: Execute immediately on first call (default: true)
|
|
89
|
-
* - Trailing: Execute after wait period if called during throttle (default: true)
|
|
90
|
-
*
|
|
91
|
-
* For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
|
|
92
|
-
*
|
|
93
|
-
* State Management:
|
|
94
|
-
* - Uses TanStack Store for reactive state management
|
|
95
|
-
* - Use `initialState` to provide initial state values when creating the throttler
|
|
96
|
-
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
97
|
-
* - The state includes execution count, last execution time, pending status, and more
|
|
98
|
-
* - State can be accessed via `throttler.store.state` when using the class directly
|
|
99
|
-
* - When using framework adapters (React/Solid), state is accessed from `throttler.state`
|
|
100
|
-
*
|
|
101
|
-
* @example
|
|
102
|
-
* ```ts
|
|
103
|
-
* const throttler = new Throttler(
|
|
104
|
-
* (id: string) => api.getData(id),
|
|
105
|
-
* { wait: 1000 } // Execute at most once per second
|
|
106
|
-
* );
|
|
107
|
-
*
|
|
108
|
-
* // First call executes immediately
|
|
109
|
-
* throttler.maybeExecute('123');
|
|
110
|
-
*
|
|
111
|
-
* // Subsequent calls within 1000ms are throttled
|
|
112
|
-
* throttler.maybeExecute('123'); // Throttled
|
|
113
|
-
* ```
|
|
114
|
-
*/
|
|
115
|
-
declare class Throttler<TFn extends AnyFunction> {
|
|
116
|
-
#private;
|
|
117
|
-
fn: TFn;
|
|
118
|
-
readonly store: Store<Readonly<ThrottlerState<TFn>>>;
|
|
119
|
-
key: string | undefined;
|
|
120
|
-
options: ThrottlerOptions<TFn>;
|
|
121
|
-
constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn>);
|
|
122
|
-
/**
|
|
123
|
-
* Updates the throttler options
|
|
124
|
-
*/
|
|
125
|
-
setOptions: (newOptions: Partial<ThrottlerOptions<TFn>>) => void;
|
|
126
|
-
/**
|
|
127
|
-
* Attempts to execute the throttled function. The execution behavior depends on the throttler options:
|
|
128
|
-
*
|
|
129
|
-
* - If enough time has passed since the last execution (>= wait period):
|
|
130
|
-
* - With leading=true: Executes immediately
|
|
131
|
-
* - With leading=false: Waits for the next trailing execution
|
|
132
|
-
*
|
|
133
|
-
* - If within the wait period:
|
|
134
|
-
* - With trailing=true: Schedules execution for end of wait period
|
|
135
|
-
* - With trailing=false: Drops the execution
|
|
136
|
-
*
|
|
137
|
-
* @example
|
|
138
|
-
* ```ts
|
|
139
|
-
* const throttled = new Throttler(fn, { wait: 1000 });
|
|
140
|
-
*
|
|
141
|
-
* // First call executes immediately
|
|
142
|
-
* throttled.maybeExecute('a', 'b');
|
|
143
|
-
*
|
|
144
|
-
* // Call during wait period - gets throttled
|
|
145
|
-
* throttled.maybeExecute('c', 'd');
|
|
146
|
-
* ```
|
|
147
|
-
*/
|
|
148
|
-
maybeExecute: (...args: Parameters<TFn>) => void;
|
|
149
|
-
/**
|
|
150
|
-
* Processes the current pending execution immediately
|
|
151
|
-
*/
|
|
152
|
-
flush: () => void;
|
|
153
|
-
/**
|
|
154
|
-
* Cancels any pending trailing execution and clears internal state.
|
|
155
|
-
*
|
|
156
|
-
* If a trailing execution is scheduled (due to throttling with trailing=true),
|
|
157
|
-
* this will prevent that execution from occurring. The internal timeout and
|
|
158
|
-
* stored arguments will be cleared.
|
|
159
|
-
*
|
|
160
|
-
* Has no effect if there is no pending execution.
|
|
161
|
-
*/
|
|
162
|
-
cancel: () => void;
|
|
163
|
-
/**
|
|
164
|
-
* Resets the throttler state to its default values
|
|
165
|
-
*/
|
|
166
|
-
reset: () => void;
|
|
167
|
-
}
|
|
168
|
-
/**
|
|
169
|
-
* Creates a throttled function that limits how often the provided function can execute.
|
|
170
|
-
*
|
|
171
|
-
* This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
|
|
172
|
-
*
|
|
173
|
-
* Throttling ensures a function executes at most once within a specified time window,
|
|
174
|
-
* regardless of how many times it is called. This is useful for rate-limiting
|
|
175
|
-
* expensive operations or UI updates.
|
|
176
|
-
*
|
|
177
|
-
* The throttled function can be configured to execute on the leading and/or trailing
|
|
178
|
-
* edge of the throttle window via options.
|
|
179
|
-
*
|
|
180
|
-
* For handling bursts of events, consider using debounce() instead. For hard execution
|
|
181
|
-
* limits, consider using rateLimit().
|
|
182
|
-
*
|
|
183
|
-
* State Management:
|
|
184
|
-
* - Uses TanStack Store for reactive state management
|
|
185
|
-
* - Use `initialState` to provide initial state values when creating the throttler
|
|
186
|
-
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
187
|
-
* - The state includes execution count, last execution time, pending status, and more
|
|
188
|
-
* - State can be accessed via the underlying Throttler instance's `store.state` property
|
|
189
|
-
* - When using framework adapters (React/Solid), state is accessed from the hook's state property
|
|
190
|
-
*
|
|
191
|
-
* @example
|
|
192
|
-
* ```ts
|
|
193
|
-
* // Basic throttling - max once per second
|
|
194
|
-
* const throttled = throttle(updateUI, { wait: 1000 });
|
|
195
|
-
*
|
|
196
|
-
* // Configure leading/trailing execution
|
|
197
|
-
* const throttled = throttle(saveData, {
|
|
198
|
-
* wait: 2000,
|
|
199
|
-
* leading: true, // Execute immediately on first call
|
|
200
|
-
* trailing: true // Execute again after delay if called during wait
|
|
201
|
-
* });
|
|
202
|
-
* ```
|
|
203
|
-
*/
|
|
204
|
-
declare function throttle<TFn extends AnyFunction>(fn: TFn, initialOptions: ThrottlerOptions<TFn>): (...args: Parameters<TFn>) => void;
|
|
205
|
-
//#endregion
|
|
206
|
-
export { Throttler, ThrottlerOptions, ThrottlerState, throttle, throttlerOptions };
|
|
207
|
-
//# sourceMappingURL=throttler.d.cts.map
|
package/dist/throttler.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"throttler.js","names":["#getEnabled","#setState","#getWait","#execute","#timeoutId","#clearTimeout"],"sources":["../src/throttler.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface ThrottlerState<TFn extends AnyFunction> {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the throttler is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Timestamp of the last function execution in milliseconds\n */\n lastExecutionTime: number\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number | undefined\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultThrottlerState<\n TFn extends AnyFunction,\n>(): ThrottlerState<TFn> {\n return {\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n nextExecutionTime: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Initial state for the throttler\n */\n initialState?: Partial<ThrottlerState<TFn>>\n /**\n * A key to identify the throttler.\n * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void\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 * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.\n */\nexport function throttlerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<\n ThrottlerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\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 * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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 collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via `throttler.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `throttler.state`\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<TFn extends AnyFunction> {\n readonly store: Store<Readonly<ThrottlerState<TFn>>> = new Store(\n getDefaultThrottlerState<TFn>(),\n )\n key: string | undefined\n options: ThrottlerOptions<TFn>\n #timeoutId: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Throttler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<ThrottlerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<ThrottlerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the throttler options\n */\n setOptions = (newOptions: Partial<ThrottlerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the throttler is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<ThrottlerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\n emitChange('Throttler', this)\n }\n\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\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: Parameters<TFn>): void => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n const now = Date.now()\n const timeSinceLastExecution = now - this.store.state.lastExecutionTime\n const wait = this.#getWait()\n\n // Handle leading execution\n if (this.options.leading && timeSinceLastExecution >= wait) {\n this.#execute(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this.#setState({\n lastArgs: args,\n })\n // Set up trailing execution if not already scheduled\n if (!this.#timeoutId && this.options.trailing) {\n // prevent large number if lastExecutionTime is undefined\n const _timeSinceLastExecution = this.store.state.lastExecutionTime\n ? now - this.store.state.lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this.#setState({ isPending: true })\n this.#timeoutId = setTimeout(() => {\n const { lastArgs } = this.store.state\n if (lastArgs !== undefined) {\n this.#execute(...lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n this.fn(...args) // EXECUTE!\n const lastExecutionTime = Date.now()\n const nextExecutionTime = lastExecutionTime + this.#getWait()\n this.#clearTimeout()\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n lastExecutionTime,\n nextExecutionTime,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n setTimeout(() => {\n if (!this.store.state.isPending) {\n this.#setState({ nextExecutionTime: undefined })\n }\n }, this.#getWait())\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#execute(...this.store.state.lastArgs)\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending 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 this.#clearTimeout()\n this.#setState({\n lastArgs: undefined,\n isPending: false,\n })\n }\n\n /**\n * Resets the throttler state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultThrottlerState<TFn>())\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via the underlying Throttler instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * // 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 AnyFunction>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute\n}\n"],"mappings":"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"}
|
package/dist/types.cjs
DELETED
|
File without changes
|
package/dist/types.d.cts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
//#region src/types.d.ts
|
|
2
|
-
/**
|
|
3
|
-
* Represents a function that can be called with any arguments and returns any value.
|
|
4
|
-
*/
|
|
5
|
-
type AnyFunction = (...args: Array<any>) => any;
|
|
6
|
-
/**
|
|
7
|
-
* Represents an asynchronous function that can be called with any arguments and returns a promise.
|
|
8
|
-
*/
|
|
9
|
-
type AnyAsyncFunction = (...args: Array<any>) => Promise<any>;
|
|
10
|
-
type OptionalKeys<T, TKey extends keyof T> = Omit<T, TKey> & Partial<Pick<T, TKey>>;
|
|
11
|
-
//#endregion
|
|
12
|
-
export { AnyAsyncFunction, AnyFunction, OptionalKeys };
|
|
13
|
-
//# sourceMappingURL=types.d.cts.map
|
package/dist/utils.cjs
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
|
|
3
|
-
//#region src/utils.ts
|
|
4
|
-
function isFunction(value) {
|
|
5
|
-
return typeof value === "function";
|
|
6
|
-
}
|
|
7
|
-
function parseFunctionOrValue(value, ...args) {
|
|
8
|
-
return isFunction(value) ? value(...args) : value;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
//#endregion
|
|
12
|
-
exports.isFunction = isFunction;
|
|
13
|
-
exports.parseFunctionOrValue = parseFunctionOrValue;
|
|
14
|
-
//# sourceMappingURL=utils.cjs.map
|
package/dist/utils.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\nexport function isFunction<T extends AnyFunction>(value: any): value is T {\n return typeof value === 'function'\n}\n\nexport function parseFunctionOrValue<T, TArgs extends Array<any>>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T {\n return isFunction(value) ? value(...args) : value\n}\n"],"mappings":";;;AAEA,SAAgB,WAAkC,OAAwB;CACxE,OAAO,OAAO,UAAU;;AAG1B,SAAgB,qBACd,OACA,GAAG,MACA;CACH,OAAO,WAAW,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG"}
|
package/dist/utils.d.cts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { AnyFunction } from "./types.cjs";
|
|
2
|
-
|
|
3
|
-
//#region src/utils.d.ts
|
|
4
|
-
declare function isFunction<T extends AnyFunction>(value: any): value is T;
|
|
5
|
-
declare function parseFunctionOrValue<T, TArgs extends Array<any>>(value: T | ((...args: TArgs) => T), ...args: TArgs): T;
|
|
6
|
-
//#endregion
|
|
7
|
-
export { isFunction, parseFunctionOrValue };
|
|
8
|
-
//# sourceMappingURL=utils.d.cts.map
|
package/dist/utils.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\nexport function isFunction<T extends AnyFunction>(value: any): value is T {\n return typeof value === 'function'\n}\n\nexport function parseFunctionOrValue<T, TArgs extends Array<any>>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T {\n return isFunction(value) ? value(...args) : value\n}\n"],"mappings":";AAEA,SAAgB,WAAkC,OAAwB;CACxE,OAAO,OAAO,UAAU;;AAG1B,SAAgB,qBACd,OACA,GAAG,MACA;CACH,OAAO,WAAW,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG"}
|