A time-based rate limiter using promises
npm install @forivall/wytwyt - time-based rate limiter
=============================






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 or setTimeout 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
``sh`
npm install --save wyt
Just put it in front of your HTTP requests.
`js
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
`
`js
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 beinterval
executed within a certain interval.
- _(number)_: The interval within which requestsPerInterval can
be executed.
Returns a function (requests?: number) => Promise 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 thatrequestsPerInterval
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 as
.
Returns a promise Promise that will resolve with the time waited asrequestsPerInterval` are
soon as another request can be made. If more than
requested at the same time the promise will reject.
Copyright (c) 2017 - 2020 Max Kueng and contributors
MIT License