How Does Event Loop Work in JavaScript: Explained Simply
event loop in JavaScript is a process that manages the execution of multiple tasks by continuously checking the call stack and the task queue. It runs tasks from the stack first and then processes asynchronous callbacks from the queue, allowing JavaScript to handle non-blocking operations smoothly.Syntax
The event loop itself does not have direct syntax you write in code, but it works behind the scenes with these parts:
- Call Stack: Where JavaScript runs your functions one by one.
- Task Queue (Callback Queue): Holds asynchronous tasks waiting to run.
- Event Loop: Checks if the call stack is empty and moves tasks from the queue to the stack.
You interact with the event loop indirectly using asynchronous functions like setTimeout(), Promises, and async/await.
setTimeout(() => { console.log('Task from the task queue'); }, 0); console.log('Task from the call stack');
Example
This example shows how the event loop handles synchronous and asynchronous code. The synchronous console.log runs first, then the setTimeout callback runs after the call stack is empty.
console.log('Start'); setTimeout(() => { console.log('Inside setTimeout'); }, 0); console.log('End');
Common Pitfalls
Many beginners expect asynchronous code like setTimeout with 0 delay to run immediately, but it always waits until the call stack is empty. Also, heavy synchronous code can block the event loop, making the UI unresponsive.
Another common mistake is misunderstanding Promises and microtasks, which run before tasks in the task queue but after the current stack.
console.log('Before'); setTimeout(() => { console.log('Timeout'); }, 0); Promise.resolve().then(() => { console.log('Promise'); }); console.log('After');
Quick Reference
| Concept | Description |
|---|---|
| Call Stack | Executes functions in order, one at a time. |
| Task Queue | Holds asynchronous callbacks waiting to run. |
| Microtask Queue | Holds promise callbacks, runs before task queue. |
| Event Loop | Moves tasks from queues to call stack when empty. |
| setTimeout | Schedules a task to run after a delay. |
| Promise.then | Schedules a microtask to run after current stack. |