How JavaScript Runs Code
JavaScript is single-threaded with one call stack. The event loop coordinates synchronous code, macrotasks, and microtasks.
The Components
- Call Stack — executes functions LIFO
- Web APIs — setTimeout, fetch, DOM events
- Microtask Queue — Promises, queueMicrotask
- Macrotask Queue — setTimeout, setInterval, I/O
Classic Interview Question
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// Output: 1, 4, 3, 2
Order: Sync → Microtasks → Macrotasks
Follow-up Questions
Q: What is the difference between microtasks and macrotasks?
Microtasks (Promises) run before the next macrotask. The browser may render between macrotasks but not between microtasks.
Q: Can you block the event loop?
Yes — long synchronous loops, heavy JSON parsing, or synchronous crypto on the main thread block UI updates.
Pro Tip
Draw the diagram: Stack → empty → drain all microtasks → one macrotask → repeat. Interviewers love this visual.