-
-
Notifications
You must be signed in to change notification settings - Fork 0
throttle()
Eugene Lazutkin edited this page Feb 25, 2026
·
7 revisions
The throttle() function is a utility designed to limit the rate at which a specified function can be invoked. It helps in scenarios where excessive calls to a function may lead to performance issues or unintended behavior.
When the throttled function is called, it starts a timer and calls the function. If the throttled function is called again before the timer expires, the call is ignored.
It is similar to audit(), but instead of waiting for the specified delay before executing with the last arguments, it executes the function on the first call and ignores subsequent calls.
- Rate Limiting: Ensures that a function is executed only once within a specified time interval.
- Flexible Parameters: Accepts any function and a delay in milliseconds.
throttle is available as a named and default export.
const throttledFn = throttle(fn, ms);-
Parameters:
-
fn: The function to be rate-limited. It can have any number of arguments. Its return value will be ignored. -
ms: The time interval (in milliseconds) within which subsequent calls to the function will be ignored.
-
- Return Value: Returns a new function that can be called with any arguments.
- TypeScript Support: Includes TypeScript self-types for better integration with TypeScript projects.
import throttle from 'time-queues/throttle.js';
// Example function to be throttled
const log = message => console.log(message);
// Create a rate-limited version of the log function
const throttledLog = throttle(log, 2000);
// Usage
throttledLog('First call'); // Executes
throttledLog('Second call'); // Ignored
setTimeout(() => throttledLog('Third call'), 1000); // Ignored
setTimeout(() => throttledLog('Fourth call'), 3000); // Executes- Function Not Executing: Ensure that the delay (ms) is set correctly and that the function is not being called too frequently.
- debounce() - Delay until input stabilizes
- Throttler - Key-based rate limiting
- sample() - Execute at regular intervals