Why event Event loop behaving differently in js



I was expecting the output to be 3->2->1 but instead my output is 1->3->2

Why I am getting differently?

setTimeout(() => {
  console.log(`1 work is done`);
  
  setTimeout(() => {
    console.log(`2 work is done`);
  }, 3000);
  
  setTimeout(() => {
    console.log(`3 work is done`);
  }, 1000);
}, 5000);

Answer

The setTimeout() timings are not correct. Your parent setTimeout() method it’s set to execute after 5000 ms, then it enters the function and the first one it triggers is the one without Timeout which is your first console.log() , after that it executes the second one which is the third console.log() and finally the console.log() in the middle.

In summary, you forgot to setTimeout() to the first console.log(). If you want that one to be the last, it should have a Timeout bigger than the second and third. Try the following snippet:

setTimeout(() => {
  
  setTimeout(() => { console.log("1 work is done") }, 2000);
  setTimeout(() => { console.log("2 work is done") }, 1000);
  console.log("3 work is done")
  
}, 1000);


Source: stackoverflow