0
0
JavascriptHow-ToBeginner · 4 min read

How Does Event Loop Work in JavaScript: Explained Simply

The 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.

javascript
setTimeout(() => {
  console.log('Task from the task queue');
}, 0);

console.log('Task from the call stack');
Output
Task from the call stack Task from the task queue
💻

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.

javascript
console.log('Start');

setTimeout(() => {
  console.log('Inside setTimeout');
}, 0);

console.log('End');
Output
Start End Inside setTimeout
⚠️

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.

javascript
console.log('Before');

setTimeout(() => {
  console.log('Timeout');
}, 0);

Promise.resolve().then(() => {
  console.log('Promise');
});

console.log('After');
Output
Before After Promise Timeout
📊

Quick Reference

ConceptDescription
Call StackExecutes functions in order, one at a time.
Task QueueHolds asynchronous callbacks waiting to run.
Microtask QueueHolds promise callbacks, runs before task queue.
Event LoopMoves tasks from queues to call stack when empty.
setTimeoutSchedules a task to run after a delay.
Promise.thenSchedules a microtask to run after current stack.

Key Takeaways

The event loop lets JavaScript run asynchronous code without blocking the main thread.
Synchronous code runs first; asynchronous callbacks wait in queues until the stack is free.
Promises use a microtask queue that runs before regular tasks from setTimeout.
Heavy synchronous tasks block the event loop and can freeze the UI.
Understanding the event loop helps write efficient, non-blocking JavaScript code.