I want an asynchronous function to run at a maximum rate of once a second.
async function update(){
await wait_for_response();
}
setInterval(update, 1000);
In the above code, if the function takes longer than a second, the next update begins before the last has finished.
If update() takes longer than 1 second, I want the next update to wait until the last update is finished, running immediately afterwards.
Is there a simple built-in method or standard practice for implementing this?
I think that setTimeout
would be a better choice in this case:
async function update() {
const t1 = new Date();
await wait_for_response();
setTimeout(update, Math.max(0, 1000 - new Date + t1));
}
update();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With