Roadmap › JavaScript (ES5 → ES2025) & TypeScript Basics › Module: Core Concepts
Lessons in this course (16)
8. The event loop, microtasks and macrotasks
Intermediate★ Must knowLesson 8 of 16
js
console.log("1: script start");
setTimeout(() => console.log("6: timeout"), 0);
Promise.resolve()
.then(() => console.log("3: promise 1"))
.then(() => console.log("5: promise 2"));
queueMicrotask(() => console.log("4: microtask"));
console.log("2: script end");
// Order: 1, 2, 3, 4, 5, 6- JavaScript runs on one main thread with a call stack.
- Web APIs (timers, fetch, DOM events) run outside JS and enqueue callbacks.
- After the current task finishes, the engine drains the microtask queue completely, then may render, then takes the next macrotask.
- Long synchronous work blocks rendering and input → use async chunks,
requestIdleCallback, or Web Workers for CPU-heavy work. - Node.js has a similar loop with phases (timers, poll, check) and
process.nextTick(runs before promise microtasks).