Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run async function every n seconds, wait if async function takes longer than n seconds

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?

like image 948
hedgehog90 Avatar asked Jan 25 '23 20:01

hedgehog90


1 Answers

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();
like image 112
Luca Rainone Avatar answered Jan 28 '23 11:01

Luca Rainone