AI solution for Interview Question on BFE.dev
18. Explain `macrotask` and `microtask`
Macrotasks
and microtasks
are two different categories of tasks that are handled by the Javascript event loop.
A macrotask
is a task that is queued in the event loop to be executed in a future iteration. Examples of tasks that are considered as macrotasks include setTimeout()
, setInterval()
, requestAnimationFrame()
, and I/O operations. The event loop will wait for all macrotasks to complete before executing any microtasks in the queue.
A microtask
, on the other hand, is a task that is executed immediately after the currently executing function completes, but before the event loop moves on to execute any macrotasks. Microtasks include promises, process.nextTick()
, and queueMicrotask()
. Since they are executed immediately, they have a higher priority than macrotasks.
In summary, macrotasks
are tasks that are executed in a future iteration of the event loop, while microtasks
are tasks that are executed immediately after the current function completes.