Last active
July 3, 2022 09:16
-
-
Save ManUtopiK/4b80ccbdff4e351a0c7ee43fb9a3bbd2 to your computer and use it in GitHub Desktop.
rate limiting javascript generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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