Answer would be Option 3
i.e. 1 7 3 5 2 6 4
.
Let us understand why:
console.log(1)
executes immediately and it outputs1
.setTimeout(() => console.log(2));
schedules a callback to the macrotask queue.Promise.resolve().then(() => console.log(3));
schedules a callback to the microtask queue.Promise.resolve().then(() => setTimeout(() => console.log(4)));
schedules a callback to the microtask queue.Promise.resolve().then(() => console.log(5));
schedules a callback to the microtask queue.setTimeout(() => console.log(6));
schedules a callback to the macrotask queue.console.log(7);
executes immediately and it outputs7
.
So far, we have 1 7
as output. Now,
Since microtasks
takes precedence over macrotasks
.
The callback scheduled via line no. 3 (console.log(3);
) executes and is printed to console.
- Output so far:
1 7 3
The callback scheduled via line no. 4 executes and sets a new macrotasks as setTimeout
callbacks are added macrotasks queue
.
The callback schedules via line no. 5 executes and is printed to console.
- Output so far
1 7 3 5
Now, comes the turn of macrotasks as all the microtasks are over.
The callback scheduled via line no. 2, 6, 4 are executed in order and printed to console.
Final output 1 7 3 5 2 6 4
To develop a deeper understanding of the Promises, Event Loop, Macrotasks/Microtasks queues, checkout