1

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.