Member-only story
Tricky Event loop, MacroTask, and Microtask question
Not a long time ago, I encountered some tricky question about event loop that requires an understanding of macrotask and microtask.
let’s take a look at this question

Have some time to understand and come out with your own answer.
Before we start going through the solution, let’s review our understanding of event loop, macrotask, and microtask. An event loop is a JS mechanism to manage the asynchronous tasks in JS single-threaded machine. Single thread means JS will execute task one by one so if there’s any asynchronous task, we don’t want that task to block the subsequent task and cause a bottleneck. Instead, JS will execute it in a memory heap and once it’s done, the callback will be pushed to a queue. There are 2 queues, macrotask queue and microtask queue. Depending on the task, it will be put in the respective queue
Example of macrotask is setTimeout
, setInterval
, setImmediate
, requestAnimationFrame
, and I/O
Example of microtask is process.nextTick
, Promises
, queueMicrotask
, and MutationObserver

How event loop works?
- dequeue and run 1 task from macrotask queue
- dequeue and run 1 task from microtask queue
- while microtask is not empty:
- go back to step 3
3. If the macrotask queue is empty, wait till a macrotask appears.
4. go back to step 1
It must be noted that the file execution is considered as 1 macro task. So, initially, all the tasks will be pushed to the call stack to be run one by one. For example, we have the following code