I am confused between JavaScript macro and micro tasks priority

Viewed 258

I was reading about micro and macro tasks in the JavaScript stack. I wrote this code:

Promise.resolve().then(function () {
      setTimeout(function () {
        console.log('from promise one');
      }, 0);
    }).then(() => {
      console.log('from promise two');
    });

    setTimeout(function () {
      console.log('from timeout');
    }, 0);

But I realized that from timeout shows faster than from promise one in the console...

As I understood, Promise. then() is a microtask and executes before macro task which from timeout is a microtask here... but why does execute the timeout first then Promise. then?

1 Answers

Important things to know:

  1. setTimeout with a timeout of 0 will run the function at the beginning of the next event loop.
  2. The callback in Promise.resolve.then() is a microtask, and will be run after all of the macrotasks in the event loop have completed.

In your code, the second setTimeout runs first at the beginning of the 2nd event loop as a macrotask, then, the callback in the Promise.resolve.then() is called as a microtask, which sets a timeout for a function to be run at the beginning of the 3rd event loop.

Check out this short video for a succinct explanation of the event loop, microtasks and macrotasks, and asynchronous programming in JavaScript.

Related