wyt (pronounced wait) is a time-based rate limiter that uses promises.
-
Limiting calls to APIs that only allow a limited number of requests within a certain period. Just call it before your HTTP requests.
-
As an alternative to
setInterval
orsetTimeout
in polling loops.If you want to run run a function every second and you use
setInterval
, your function might run multiple times at the same time if your function occasionally takes more than 1 second to run. This might cause problems.Alternatively, if you use
setTimeout(update, 1000)
in a recursive update loop, your update interval will be 1000ms plus the time it takes for your update function to run. You'd have to measure the time and dynamically set the timeout.wyt takes care of this for you. It'll make sure that your update function runs every second unless the update function takes more than 1s to run, in which case it will run it again immediately.
- Promise-based API
- Full test coverage
- TypeScript support
- Easy to use
npm install --save wyt
Just put it in front of your HTTP requests.
import wyt from 'wyt';
// 5 API calls per second
const rateLimit = wyt(5, 1000);
async function getStuff() {
await rateLimit();
const response = await fetch('/stuff');
return response.json();
}
await getStuff();
await getStuff();
await getStuff();
await getStuff();
await getStuff();
await getStuff(); // has to wait unless the previous 5 calls together took longer than 1000ms
import wyt from 'wyt';
// Once per second
const rateLimit = wyt(1, 1000);
async function update() {
await rateLimit();
await updateMyStuff();
update();
}
update();
If, for example, updateMyStuff()
takes 900ms then rateLimit()
will wait only 100ms.
requestsPerInterval
(number): The number of requests that can be executed within a certain interval.interval
(number): The interval within whichrequestsPerInterval
can be executed.
Returns a function (requests?: number) => Promise<number>
that can be called
before before requesting a rate-limited resource in order to not exceed the
limit.
requests
(number, optional, default: 1): The number of requests that will be used at the same time. For example, if your code fetches two resources in parallel. You can not use more requests at the same time asrequestsPerInterval
.
Returns a promise Promise<number>
that will resolve with the time waited as
soon as another request can be made. If more than requestsPerInterval
are
requested at the same time the promise will reject.
Copyright (c) 2017 - 2020 Max Kueng and contributors
MIT License