V8 Engine, Single-Threaded Event Loop (Microtasks vs Macrotasks)
1Concept
JavaScript runs on a single thread powered by an Event Loop (V8 Engine + Libuv in Node.js). The Call Stack executes synchronous code. Microtasks (Promise.then, queueMicrotask) take highest priority and drain completely before Macrotasks (setTimeout, setInterval, I/O) execute.
2Architecture Diagram
[ Call Stack (Sync) ] ──► [ Microtask Queue (Promises) ] ──► [ Macrotask Queue (setTimeout/IO) ]
▲ │
└──────────────(Event Loop)──────┘3Code Example
Stage 0 Language Foundations
console.log("1. Synchronous Start");
setTimeout(() => {
console.log("4. Macrotask (setTimeout 0ms)");
}, 0);
Promise.resolve().then(() => {
console.log("3. Microtask (Promise.then)");
});
console.log("2. Synchronous End");4Expected Output
1. Synchronous Start 2. Synchronous End 3. Microtask (Promise.then) 4. Macrotask (setTimeout 0ms)
5Key Takeaways
- ✓Microtasks always drain before the next macrotask executes.
- ✓Never block the single thread with long synchronous loops.
- ✓JavaScript uses non-blocking asynchronous I/O.