2

I need a simple way to wait for setTimeout code to finish executing and then run the code that comes after setTimeout. Now the code after loop containing setTimout is executing before loop/setTimout is finished executing.

for(let i = 0; i < 5; i++) {
   setTimeout(function(){
    console.log(i);
  }, i*1000);
 }
console.log("loop/timeout is done executing");
3

3 Answers 3

5

setTimeout is by definition not synchronous - whatever you use to solve the issue will have to be asynchronous, there's no way around that.

The best way to achieve something like this is to use Promises instead, calling Promise.all on an array of the created promises:

(async () => {
  await Promise.all(Array.from(
    { length: 5 },
    (_, i) => new Promise(res => setTimeout(() => {
      console.log(i);
      res();
    }, i * 1000))
  ));
  console.log("loop/timeout is done executing");
})();

Although await is awaiting a Promise, and Promises aren't synchronous, if you're want the code to look flat so you can have the final console.log on the same indentation level as the main function block, this is probably the way to go.

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

Comments

2

you can define a function and call that function inside the timeout

    let currentForId = 0;
    for(let i = 0; i < 5; i++) {
       setTimeout(function(){
        console.log(i);
        if(++currentForId == 5)
        calling("message");
      }, i*1000);
     }


    function calling(msg){
       console.log(msg);
       console.log("loop/timeout is done executing");
    }
    

4 Comments

do you want all the timeouts to complete before printing ??
yeah, now you'll be calling calling 5 times - again, not what was asked :p
yes I like the simplicity of your answer but I want call the calling only once after the loop is done.
now you have one callback after all the timeouts iterated
0

The code/message you need to run at the end of the count needs to be inside the for loop. Here's a simple way to achieve this.

for (let i = 0; i < 5; i++) {
    setTimeout(function () {
        console.log(i);
        if (i == 4) {
            console.log("loop/timeout is done executing");
        }
    }, i * 1000);
}

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.