Skip to content Skip to sidebar Skip to footer

Simple Way To Synchronously Execute Code After SetTimout() Code Is Done

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 bef

Solution 1:

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.


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

Solution 3:

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

Post a Comment for "Simple Way To Synchronously Execute Code After SetTimout() Code Is Done"