Event Loop in JavaScript
By Saket Bhatnagar••Intermediate
event loop
- 1JavaScript is single-threaded — it can only do one thing at a time.
- 2But modern JavaScript supports asynchronous operations like setTimeout, Promises, fetch, etc.
- 3To handle these async tasks, JS uses an internal program called the “Event Loop”.
- 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.
- 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.
- 6Once they finish (like timer ends or fetch returns), their callbacks are sent to Queues.
- 7There are two queues:
- Microtask Queue (handles Promises, MutationObserver)
- Callback Queue (handles setTimeout, setInterval, etc.)
- 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.
- 9The Event Loop first checks if the Call Stack is empty.
- 10If Call Stack is empty, it pushes tasks from the Microtask Queue first to call stack.
- 11After Microtask Queue is empty, it pushes next task from the Callback Queue.
- 12This continuous checking and execution is done by the Event Loop.
- 13This is how JS handles non-blocking code even though it’s single-threaded.
- 14This process of checking and pushing continues endlessly — that’s why it’s called an “event loop.”
- 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.
- 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?