← All posts
postMay 2, 2026
Explain the JS Event Loop
#javascript#event-loop#async#interview
How does the JavaScript event loop work? Explain the call stack, task queue, and microtask queue.
The JS engine runs on a single thread with one call stack. The event loop is a mechanism that: 1. Runs all synchronous code to completion (call stack empties) 2. Processes ALL microtasks (Promise .then/.catch, queueMicrotask) — queue must fully drain 3. Takes ONE task from the macrotask queue (setTimeout, setInterval, I/O events) 4. Renders if needed 5. Repeats Key rule: microtasks run between every macrotask, not after all macrotasks. ```js console.log('1'); // sync setTimeout(() => console.log('4'), 0); // macrotask Promise.resolve().then(() => console.log('3')); // microtask console.log('2'); // sync // Output: 1, 2, 3, 4 ```