Inner Workings

Here are the details of how it works under the hood within a browser:One or more threads (eg. spawned as Web Workers) may run within a browser. Each thread gets its own event loop. Within an event loop, there are a call stack, a microtask queue, and one or more macrotask queues. As the execution of the main event loop begins, the event loop first intelligently picks a macrotask queue. The event loopthen takes and runs the oldest task in the queue. In the process, jobs may be pushed to the microtask queue, such as when a Promise or a MutationObersver is encountered.

As the macrotask ends (ie. the call stack becomes empty), ALL the jobs in the microtask queue are sequentially executed. During the process, more jobs/microtasks may be queued. When the microtask queue becomes empty, the browser may perform updates to the user interface.The process repeats, ie. the event loop starts picking a macrotask queue again, and runs the oldest task in it.