Skip to content

Instantly share code, notes, and snippets.

@ManUtopiK
Last active July 3, 2022 09:16
Show Gist options
  • Select an option

  • Save ManUtopiK/4b80ccbdff4e351a0c7ee43fb9a3bbd2 to your computer and use it in GitHub Desktop.

Select an option

Save ManUtopiK/4b80ccbdff4e351a0c7ee43fb9a3bbd2 to your computer and use it in GitHub Desktop.
rate limiting javascript generator
async function* rateLimit(limit, time) {
let count = 0;
while(true) {
if(count++ >= limit) {
await delay(time);
count = 0;
}
yield; // Let's execute next code
}
}
async function delay(delayInms) {
return new Promise(resolve => {
setTimeout(() => {
resolve(2);
}, delayInms);
});
}
// test
const userAPIRate = rateLimit(10, 3000);
async function getUser(id) {
await userAPIRate.next();
return console.log(id); // call to api: fetch("/user/", id);
}
for (let i = 0; i < 30; i++) {
getUser(i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment