While reading a few articles about Event Loop and how it works I came across this quote:
Immediately after every macrotask, the engine executes all tasks from microtask queue, prior to running any other macrotasks or rendering or anything else.
And the quote kinda confused me, so I'd like to share my thoughts on that, and then hear whether I'm thinking in the right direction, or I'm dead wrong
At beginning, this quote sounded like macrotasks have priority over microtasks, and I ran following code:
const resolvedPromise = Promise.resolve('Microtask (Promise)');
setTimeout(() => {
console.log('Macrotask (setTimeout)'); // (3)
}, 0);
resolvedPromise.then(data => console.log(data)); // (2)
console.log('Synchronous Code'); // (1)
As it turned out, the order was still synchronous code first, then microtask followed by macrotask, which got me confused. Then, I googled more and found that some say that the first macrotask is the script itself.
So, basically, whole script is being executed and at that moment other macrotasks & microtasks are being put into their respective queues. After reaching the last line of code, Microtasks are executed, then newly found macrotasks from macrotask queue (I believe I can say Callback Queue too, right?) are being executed, and if any macrotask introduces a new microtask, then when that macrotask stops executing, the new microtask is executed, and so on.