What is p-throttle?
The p-throttle npm package is used to throttle the execution of asynchronous functions. It allows you to limit the number of times a function can be called over a specified period, which is useful for rate-limiting API requests or controlling the flow of operations in a system.
What are p-throttle's main functionalities?
Basic Throttling
This feature allows you to throttle the execution of a function. In this example, the function can only be called twice per second.
const pThrottle = require('p-throttle');
const throttle = pThrottle({ limit: 2, interval: 1000 });
const throttled = throttle(async (index) => {
console.log(index);
});
(async () => {
for (let i = 0; i < 10; i++) {
throttled(i);
}
})();
Throttling with Promises
This feature demonstrates throttling with asynchronous functions that return promises. The function is throttled to execute once every two seconds.
const pThrottle = require('p-throttle');
const throttle = pThrottle({ limit: 1, interval: 2000 });
const throttled = throttle(async (index) => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(index);
resolve();
}, 1000);
});
});
(async () => {
for (let i = 0; i < 5; i++) {
await throttled(i);
}
})();
Other packages similar to p-throttle
bottleneck
Bottleneck is a powerful rate limiter that can be used to control the rate of asynchronous operations. It offers more advanced features like clustering and priority queues, making it more suitable for complex scenarios compared to p-throttle.
limiter
Limiter is another rate-limiting library that provides a simple way to limit the number of operations over a given time period. It is similar to p-throttle but offers a more straightforward API for basic use cases.
rate-limiter-flexible
Rate-limiter-flexible is a highly flexible rate-limiting library that supports various backends like Redis and MongoDB. It provides more configuration options and is suitable for distributed systems, offering more flexibility than p-throttle.
p-throttle
Throttle promise-returning & async functions
It also works with normal functions.
It rate-limits function calls without discarding them, making it ideal for external API interactions where avoiding call loss is crucial.
Install
npm install p-throttle
Usage
Here, the throttled function is only called twice a second:
import pThrottle from 'p-throttle';
const now = Date.now();
const throttle = pThrottle({
limit: 2,
interval: 1000
});
const throttled = throttle(async index => {
const secDiff = ((Date.now() - now) / 1000).toFixed();
return `${index}: ${secDiff}s`;
});
for (let index = 1; index <= 6; index++) {
(async () => {
console.log(await throttled(index));
})();
}
API
pThrottle(options)
Returns a throttle function.
options
Type: object
Both the limit
and interval
options must be specified.
limit
Type: number
The maximum number of calls within an interval
.
interval
Type: number
The timespan for limit
in milliseconds.
strict
Type: boolean
Default: false
Use a strict, more resource intensive, throttling algorithm. The default algorithm uses a windowed approach that will work correctly in most cases, limiting the total number of calls at the specified limit per interval window. The strict algorithm throttles each call individually, ensuring the limit is not exceeded for any interval.
onDelay
Type: Function
Get notified when function calls are delayed due to exceeding the limit
of allowed calls within the given interval
.
Can be useful for monitoring the throttling efficiency.
In the following example, the third call gets delayed and triggers the onDelay
callback:
import pThrottle from 'p-throttle';
const throttle = pThrottle({
limit: 2,
interval: 1000,
onDelay: () => {
console.log('Reached interval limit, call is delayed');
},
});
const throttled = throttle(() => {
console.log('Executing...');
});
await throttled();
await throttled();
await throttled();
throttle(function_)
Returns a throttled version of function_
.
function_
Type: Function
A promise-returning/async function or a normal function.
throttledFn.abort()
Abort pending executions. All unresolved promises are rejected with a pThrottle.AbortError
error.
throttledFn.isEnabled
Type: boolean
Default: true
Whether future function calls should be throttled and count towards throttling thresholds.
throttledFn.queueSize
Type: number
The number of queued items waiting to be executed.
Related
- p-debounce - Debounce promise-returning & async functions
- p-limit - Run multiple promise-returning & async functions with limited concurrency
- p-memoize - Memoize promise-returning & async functions
- More…