Logo
HTMLCSSJavaScriptReactjsnewContactUpdates

Get started today

HTMLCSSJavaScriptReactjsnewContactUpdates

Tools

Resume BuilderQR GeneratorVS Code Editor

Connect

GitHubWhatsApp Channel
what is promise
frequently asked questions

Event Loop in JavaScript

By Saket Bhatnagar•August 17, 2025•Intermediate

Table of Contents

  1. event loop

event loop

  1. 1JavaScript is single-threaded — it can only do one thing at a time.
  2. 2But modern JavaScript supports asynchronous operations like setTimeout, Promises, fetch, etc.
  3. 3To handle these async tasks, JS uses an internal program called the “Event Loop”.
  4. 4Definition: The Event Loop is a program inside the JS engine that helps JavaScript run async tasks by constantly checking the call stack and picking tasks from queues when the stack is empty.
  5. 5Async functions like setTimeout or Promises don’t run immediately — they are sent to the Web API (provided by browser or Node.js) to be processed.
  6. 6Once they finish (like timer ends or fetch returns), their callbacks are sent to Queues.
  7. 7There are two queues:
    • Microtask Queue (handles Promises, MutationObserver)
    • Callback Queue (handles setTimeout, setInterval, etc.)
  8. 8Microtask Queue has high priority over Callback Queue which means if we have setTimeout and Promise.then execution at the same time, the Promise will be executed first.
  9. 9The Event Loop first checks if the Call Stack is empty.
  10. 10If Call Stack is empty, it pushes tasks from the Microtask Queue first to call stack.
  11. 11After Microtask Queue is empty, it pushes next task from the Callback Queue.
  12. 12This continuous checking and execution is done by the Event Loop.
  13. 13This is how JS handles non-blocking code even though it’s single-threaded.
  14. 14This process of checking and pushing continues endlessly — that’s why it’s called an “event loop.”
  15. 15💡 Real-Life Analogy: Imagine a traffic system with a single-lane road:
    • 👮 Traffic Cop = Event Loop → manages which car (task) goes when
    • 🛣️ Road = Call Stack → only one car (task) allowed at a time
    • 🅿️ Parking Lots = Web APIs → async tasks wait here until ready
    • 🚗 Car = Function/Callback → tasks that want to run
    • 📥 Queue = Callback or Microtask Queue → where cars line up after being ready
    • The Cop (Event Loop) only lets a new car enter when the road is fully empty.
    • In short: Event Loop helps JavaScript handle async code without blocking the main thread.
  16. 16Interview Questions:
    • Which tasks get higher priority: callbacks (setTimeout) or microtasks (Promises)?
    • Can you explain Event Loop with a real-life example?
    • Explain the execution order of the following: setTimeout, Promise.then, normal console.log?

Share this article

Last updated: August 17, 2025

Join Our Community

Login to Join

© 2025 Saket Bhatnagar. All rights reserved.