totalnoob
totalnoob

Reputation: 2741

macrotask queue and microtask queue priority

bit confused with this description of the macrotask and the microtask queue.

For each loop of the ‘event loop’ one macrotask is completed out of the macrotask queue. After that macrotask is complete, the event loop visits the microtask queue. The entire microtask queue is completed before moving on.

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

Promise.resolve().then(function() {
  console.log('microtask 1');
}).then(function() {
  console.log('microtask 2');
});

Shouldn't this code output 'macrotask' first? as setTimeout is part of the macrotask queue that is completed before the loop goes to the microtask queue?

Upvotes: 0

Views: 1321

Answers (2)

Pravin Divraniya
Pravin Divraniya

Reputation: 4384

At the execution of any JS file, the JS engine wraps the contents in a function and associates the function with an event either start or launch. The JS engine emits the start event, the events are added to the task queue (as a macrotask).

On initialization, the JS engine first pulls off the first task in the macrotask queue and executes the callback handler. Thus, our code is run.

So we see the script running is the first macrotask queued. So first JSEngine adds all the synchronous code in script as a macrotask in the event-loop queue. Then it sees setTimeout which is another macrotask so it is logged in a separate task in the event-loop queue. Then it sees Promise which is a microtask and adds it in microtask queue.

The microtask queue is processed after callbacks as long as no other JavaScript is mid-execution and at the end of each task.

So the sequence of task queue, in this case, is Script=>Promise1=>Promise2=>setTimeout

As there is no synchronous code in the script so the execution of script prints nothing. Then Engine executes microtask queue(promise-1,promise-2) and in the end macrotask which is setTimeout.

enter image description here

Note:- This is default behavior and may differ in different browsers.

Upvotes: 1

Radu Diță
Radu Diță

Reputation: 14201

The task your code is running is actually a macrotask.

When that finishes (this means evaluating and running your code) the event loop will execute the microtasks that are in the queue. That is the first promise, but that promise adds another promise to the microtask q and the second promise is executed.

After the microtask q is cleared another macrotask is picked, and eventually, the timeout is executed.

Upvotes: 2

Related Questions