Search code examples
javascriptsettimeoutsynchronous

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

Solution

  • 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.