I am looking to set a delay in making http requests to avoid going over the rate limit of the external server.
users.forEach(async function(user) {
await rate_check()
make_http_request()
})
I need help with implementing the rate_check function in a way that would avoid busy waiting. At the moment, I am busy waiting as follows
async function rate_check() {
if(rate_counter < rate_limit)
rate_counter += 1
else {
// Busy wait
while(new Date() - rate_0_time < 1000) {}
rate_counter = 1
time_delta = new Date() - rate_0_time
rate_1_time = new Date()
}
}
await new Promise(resolve => { setTimeout(resolve, 2000)})
does not work as it would only cause rate_check to sleep, but the anonymous function would continue to make requests.
Any rate checking code must be done in the rate_check function and not in the function where the http request happens as requests happen across multiple async functions and they are making requests to the same server.
I am open to any other suggestions as well as refactoring as long as it avoids nesting callbacks or third-party dependency