JavaScript Interview Question #75

What is the difference between microtasks and macrotasks/tasks?

DOM, Events & Event Loop Fundamentals Mid-Level Intermediate

Quick Interview Answer

Microtasks include promise reaction callbacks and queueMicrotask callbacks. Tasks, often informally called macrotasks, include work such as timer callbacks and many browser events.

Detailed Explanation

Microtasks include promise reaction callbacks and queueMicrotask callbacks. Tasks, often informally called macrotasks, include work such as timer callbacks and many browser events.

After the current JavaScript execution completes, the runtime drains the microtask queue before taking the next task. This is why an already-resolved Promise callback normally executes before a setTimeout callback scheduled with zero delay.

Code Example

console.log("1");

setTimeout(() => console.log("2"), 0);

queueMicrotask(() => console.log("3"));

Promise.resolve()
    .then(() => console.log("4"));

console.log("5");

// 1, 5, 3, 4, 2