Eventloop in NodeJS: MacroTasks and MicroTasks
This document talks about various queues concerning EventLoop to better understand how best to use Promises, Timers (setTimeout etc)
V8 Engine works by enqueuing tasks into the event loop.
But, deep down the task queue, something else is going on. The tasks are broken down further into microtask and macrotask
- macroTasks: setTimeout, setInterval, setImmediate, requestAnimationFrame, I/O, UI rendering
- microTasks: process.nextTick, Promises, queueMicrotask, MutationObserver
Only after tasks in microTasks are completed/ excahusted, event loop will next pick up one task from macroTasks. And this repeats.
If microtasks continuously add more elements to microTasks queue, macroTasks will stall and won’t complete event loop in shorter time causing event loop delays.
Visualize order of execution of macro vs microtasks here.
Try in local…
// node macro_and_micro_tasks.js
Precedence within Eventloop
callstack > one macroTasks> all microTasks
So when to use what?
Basically, use microtasks when you need to do stuff asynchronously in a sequence (i.e. when you would say perform this (micro-)task in the most immediate future). Otherwise, stick to macrotasks.
- Tasks are picked from the Micro and Macro task Queues.
- In above reference Task is referred as Macro task
- Microtasks are processed when the current task(operation) ends and the microtask queue is cleared before the next macrotask cycle.
- Microtasks can enqueue other microtasks. All are executed before the next task inline.
- UI rendering is run after all microtasks execution (NA for nodejs).