Reputation: 13
I'm trying to get a loop working with a longer delay, when the task takes longer as planned.
currently I'm using this code for the loop:
async function doSomeStuff() {
// do some stuff
// sometimes this action may take longer than 5 seconds
// after finishing wait 5 seconds
console.log('task completed, waiting 5 seconds for next run...');
}
setInterval(doSomeStuff, 5000);
works like a charm, but the delay is fixed at 5 seconds, even if the tasks takes longer as planned, so that sometimes the new loop starts only 1 second after finishing the last one instead of waiting 5 seconds.
unfortunately, I was not able to solve it myself by looking at the other questions.
I am grateful for any help.
Best regards Paedda
Upvotes: 1
Views: 2944
Reputation: 3471
You were almost there
async function doSomeStuff() {
// do some stuff
// sometimes this action may take longer than 5 seconds
// after finishing wait 5 seconds
console.log('task completed, waiting 5 seconds for next run...');
setTimeout(doSomeStuff, 5000);
}
Upvotes: 0
Reputation: 222309
async
functions shouldn't be used with API that ignores a promise that it returns such as setInterval
, in case it's expected that a promise should be chained.
This can be done with recursive async
function:
(async function doSomeStuff() {
await new Promise(resolve => setTimeout(resolve, 5000));
// do some stuff
await doSomeStuff();
})();
Or infinite loop:
(async function doSomeStuff() {
while (true) {
await new Promise(resolve => setTimeout(resolve, 5000));
// do some stuff
}
})();
Function body can be wrapped with try..catch
if needed to handle errors.
Upvotes: 6