🔁 Event Loop & Event Bubbling

Last Updated: 27th October 2025


  • The Event Loop is the core mechanism that makes JavaScript asynchronous.
  • It helps JS handle multiple tasks without blocking the main thread — even though JS runs single-threaded.

🧠 How It Works

  1. Call Stack: This is where JavaScript keeps track of functions currently being executed.
  2. Web APIs / Node APIs: These handle async tasks (like setTimeout, fetch, or DOM events) outside the main thread.
  3. Callback Queue / Task Queue: Once async tasks finish, their callback functions move here, waiting for execution.
  4. Event Loop: Keeps checking — “Is the call stack empty?”.If yes, it moves the next callback from the queue to the stack.

⚙️ Visual Flow Example

Call Stack    Web API           Task Queue
-----------   --------          -----------
main()        setTimeout() →    (after delay)

➡ JS executes main() ➡ setTimeout() goes to Web API ➡ After delay, its callback is queued ➡ Event Loop moves it to Stack when empty


Example:

console.log("1");

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

console.log("3");
// Output:
// 1
// 3
// 2

🗣 Hinglish Tip:Event loop bolta hai — “pehle main kaam khatam karu, phir queue wale kaam kar lunga!” That’s why 2 prints at the end even though its delay is 0


🌀 Event Bubbling

When an event (like click) happens on a nested element, it bubbles up (travels upwards) through its parent elements in the DOM tree.

<div id="parent">
  <button id="child">Click Me</button>
</div>

<script>
  document.getElementById("parent").addEventListener("click", () => {
    console.log("Parent clicked");
  });

  document.getElementById("child").addEventListener("click", () => {
    console.log("Child clicked");
  });
</script>

Output:

Child clicked
Parent clicked

Event first triggers on child,then bubbles up to the parent.

Note : You can You can stop bubbling using:event.stopPropagation();