The event loop is the mechanism that allows JavaScript — a single-threaded language — to handle asynchronous operations like timers, HTTP requests, and I/O without blocking the main thread.
Even though JavaScript executes code line by line, the event loop lets async tasks run in the background and continue execution once they’re ready.
1️⃣ JavaScript Execution Model
- Call Stack – Keeps track of functions to execute.
- Web APIs / Node APIs – Handle async tasks like
setTimeout,fetch, I/O. - Callback Queue / Task Queue – Stores callbacks to run once the stack is empty.
- Event Loop – Monitors the call stack and callback queue, pushing callbacks to the stack when it’s empty.
2️⃣ Flow of Async Code
console.log("Start");
setTimeout(() => {
console.log("Timeout finished");
}, 0);
console.log("End");
Execution:
console.log("Start")→ prints StartsetTimeout→ registered in Web API with 0ms timerconsole.log("End")→ prints End- Event loop sees stack is empty → moves
setTimeoutcallback to stack console.log("Timeout finished")→ prints Timeout finished
✅ Output:
Start
End
Timeout finished
3️⃣ Microtasks vs Macrotasks
Macrotasks (Task Queue):
- Examples:
setTimeout,setInterval,setImmediate, I/O callbacks - Executed after the call stack is empty
Microtasks (Microtask Queue):
- Examples:
Promise.then,MutationObserver,queueMicrotask - Executed before the next macrotask, immediately after the current stack
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
✅ Output:
Start
End
Promise
Timeout
Explanation:
Promise.thengoes to microtask queue, runs beforesetTimeout(macrotask).
4️⃣ Key Takeaways
- JS is single-threaded, but async tasks are offloaded to Web APIs / Node APIs.
- The event loop keeps the program responsive by checking the call stack and queues.
- Microtasks have higher priority than macrotasks.
- This mechanism allows non-blocking I/O, smooth UI updates, and async handling.
⚡ In short:
The event loop is JavaScript’s way of handling asynchronous operations in a single thread. Async tasks like Promises and timers are executed in microtask and macrotask queues, ensuring non-blocking, responsive code execution.