🔁 Event Loop in JavaScript

🎯 What is the Event Loop?

The Event Loop is a core mechanism in JavaScript that enables asynchronous programming. It ensures non-blocking behavior by managing the execution of multiple chunks of code over time — even though JavaScript is single-threaded.

Note

JavaScript executes code inside a single thread, but the Event Loop allows it to handle async tasks like timers, promises, and I/O without freezing the UI.

🧩 The Building Blocks

  • Call Stack — handles function execution.
  • Web APIs — provided by the browser (e.g., setTimeout, DOM events).
  • Callback Queue — stores tasks waiting to be run after the stack is clear.
  • Microtask Queue — stores resolved promises and has higher priority than the callback queue.

🔄 How the Event Loop Works

1. Executes all synchronous code in the call stack.
2. Checks the microtask queue and runs all microtasks.
3. Takes the first task from the callback queue and executes it.
4. Repeats the process — this is the loop!

⚙️ Example: setTimeout vs Promises

Event Loop Behavior

console.log("Start");

setTimeout(() => {
  console.log("Timeout");
}, 0);

Promise.resolve().then(() => {
  console.log("Promise");
});

console.log("End");

🧠 Output:

Code Snippet

Start
End
Promise
Timeout

Note

Promise (microtask) runs before setTimeout (callback), even if both are scheduled at the same time.

🖼️ Visual Representation

Media content

🚨 Common Mistake: Thinking setTimeout is Immediate

Even with setTimeout(..., 0), the callback goes into the queue and is delayed until the call stack and microtasks are cleared.

📚 Summary

  • JavaScript uses the Event Loop to handle asynchronous operations.
  • Promises and MutationObserver go into the microtask queue.
  • setTimeout, setInterval, and DOM events go into the callback queue.
  • Microtasks are always processed before callbacks.
>>“Understanding the Event Loop is the key to mastering JavaScript’s concurrency model.”

🔗 References