Now, after this desired time, the code needs to be passed to the Call Stack, but this Call Stack doesn’t provide a timer by which we can delay the execution of the code. So, it uses the help of a web API setTimeout() which is available in the window global object in the browser. After a certain time period, Call Stack gets the code through Event Loop which fetches the Callback functions to Call Stack. But, Callback functions can’t directly go to the Event loop.
So, here comes the role of Microtask Queue and Callback Queue. These Queues work as a mediator, once the timer gets expired the callback functions are put inside these queues serially. And whenever the Call stack is empty, the event loop fetches them to Call Stack in FIFO order.
But, we need Microtask Queue and Callback Queue for different purposes. Let’s see the comparison between them.
Callback Queue: After the timer gets expired, the callback function is put inside the Callback Queue, and the Event Loop checks if the Call Stack is empty and if empty, pushes the callback function from Callback Queue to Call Stack and the callback function gets removed from the Callback Queue. Then the Call Stack creates an Execution Context and executes it.
|Callback Queue||Microtask Queue|
|Callback Queue gets the ordinary callback functions coming from the setTimeout() API after the timer expires.||Microtask Queue gets the callback functions coming through Promises and Mutation Observer.|
|Callback Queue has lesser priority than Microtask Queue of fetching the callback functions to Event Loop.||Microtask Queue has higher priority than Callback Queue of fetching the callback functions to Event Loop.|