The JavaScript Event Loop Explained
JS جاوااسکریپت

The JavaScript Event Loop Explained

Understand call stack, task queue, microtasks, and ace the classic async output questions.

BugCast Admin··۱۰ دقیقه مطالعه

How JavaScript Runs Code

JavaScript is single-threaded with one call stack. The event loop coordinates synchronous code, macrotasks, and microtasks.

The Components

  1. Call Stack — executes functions LIFO
  2. Web APIs — setTimeout, fetch, DOM events
  3. Microtask Queue — Promises, queueMicrotask
  4. 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.

#event-loop#async#interview

مطالب مرتبط