rate-limit-threshold
v0.2.0
Published
Rate limiter with a maximum number of calls per given period of time
Downloads
1,284
Maintainers
Readme
rate-limit-threshold
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.
Installation
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.
Compatibility
This package is compatible with:
Sponsor
If you find this package useful and would like to support the development of open-source projects, please consider sponsoring or making a contribution. Your support helps sustain ongoing development and improvements.
Some of my other projects you may want to support include:
or
Usage
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
}
})();
API Documentation
RateLimitThreshold
Constructor
Create an instance of RateLimitThreshold with the following syntax:
new RateLimitThreshold(requests, period);
Parameters:
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.
limit
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();
Returns:
A promise that resolves after a delay, with the time (in milliseconds) that the execution was paused.