Module designed to handle rate-limiting by allowing developers to set thresholds for the maximum number of requests that can be made within a specified time period. This helps to prevent exceeding the rate limits imposed by APIs or services. The module provides configurable options and is useful for managing API consumption in a controlled manner.
npm install rate-limit-threshold
This package is an ESM (ECMAScript Module) package. Therefore, your project must also use the ESM format. For more details, refer to this guide.
This package is compatible with:
If you find this project useful and would like to support its development, consider sponsoring or contributing:
-
Buy me a coffee:
A rate-limit-threshold
helps enforce rate limits by restricting the maximum number of calls allowed within a specified time frame.
More information about rate limiting can be found here.
Example
import { RateLimitThreshold } from 'rate-limit-threshold';
(async () => {
const rateLimitThreshold = new RateLimitThreshold(3, 1); // Allow a maximum of 3 requests per second
for (let n = 0; n < 7; ++n) {
const delayInMs = await rateLimitThreshold.limit(); // Apply delay to comply with the rate limit
console.log('Timeout applied to comply with rate limit:', delayInMs);
// After the limit() has been applied, proceed with your rate-limited request
}
})();
Create an instance of RateLimitThreshold with the following syntax:
new RateLimitThreshold(requests, period);
requests
(number): The maximum number of requests allowed within the specified period.period
(number): The time period (in seconds) within which the specified number of requests are allowed.
The limit()
method ensures that the number of function calls does not exceed the specified requests within the given period.
This method should be called before the function you wish to rate limit.
const timeSleptInMs = await rateLimitThreshold.limit();
A promise that resolves after a delay, with the time (in milliseconds) that the execution was paused.