JavaScript Event Loop
The Fundamental Problem
JavaScript is single-threaded. This means it has only one call stack and can execute only one piece of code at a time. Imagine a restaurant with just one chef who can only cook one dish at a time. If that chef has to wait for water to boil, the entire kitchen comes to a standstill, right?
But wait — JavaScript handles network requests, timers, user interactions, and animations all at the same time without freezing your browser. How is this possible?
Get Urvi Bhavsar’s stories in your inbox
Join Medium for free to get updates from this writer.
Enter the Event Loop — JavaScript’s ingenious solution to achieve asynchronous, non-blocking behavior while remaining single-threaded.
How the Event Loop Works?
The event loop continuously checks whether the call stack is empty and whether there are pending tasks in the callback queue or microtask queue.
- Call Stack: JavaScript has a call stack where function execution is managed in a Last-In, First-Out (LIFO) order.
- Web APIs (or Background Tasks): Web APIs are not part of the JavaScript engine. They’re provided by the browser (or Node.js runtime) and handle asynchronous operations in the background. These include setTimeout, setInterval, fetch, DOM events, and other non-blocking operations.
- Microtask Queue(High Priority Tasks / Job Queue): Promises and other microtasks go into the microtask queue, which is processed before the task queue.
What goes into the Microtask Queue:
1.process.nextTick()in Node.js: This has special priority —
It runs before any other microtasks.
It’s handled by a separate internal queue that executes immediately after synchronous code.
1. Promise callbacks (.then(),.catch(),.finally())
2.async/awaitcontinuations
3.queueMicrotask()
5.MutationObservercallbacks - Callback Queue (Task Queue / Macrotask Queue): When an asynchronous operation is completed, its callback is pushed into the task queue.
What goes into the Microtask Queue:
1.setTimeoutcallbacks
2.setIntervalcallbacks
3.setImmediate()(Node.js)
4. I/O operations
5. UI rendering events
6. DOM event callbacks (click, scroll, etc.) - Event Loop: It continuously checks the call stack and, if empty, moves tasks from the queue to the stack for execution.








