Eventloop in NodeJS: MacroTasks and MicroTasks

Jeevan D C
Feb 10, 2021 · 2 min read

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

Microtasks Queue and MacroTask Queue
  1. macroTasks: setTimeout, setInterval, setImmediate, requestAnimationFrame, I/O, UI rendering

Only after tasks in microTasks are completed, event loop will next pick up tasks from macroTasks.

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
A
B
C
D
E
F
G
H
I
J

Precedence within Eventloop

callstack > one macroTasks> all microTasks

Try here

So when to use what?

Basically, use microtasks when you need to do stuff asynchronously in a synchronous way (i.e. when you would say perform this (micro-)task in the most immediate future). Otherwise, stick to macrotasks.

  • Tasks are taken from the Task (MacroTask) Queue.

Like to learn by sharing knowledge? You might want to check out our team! Join us in making the next life-centric digital solutions!

Dkatalis

building growth and excellence, enabled by technology