Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 11: The Event Loop & Concurrency

1. The Architecture of the Browser

To understand how JS handles multiple tasks, we have to look at the three main components working together:

  1. The Call Stack: Where your code is executed (Last In, First Out).
  2. Web APIs: Provided by the browser (not the JS engine), like setTimeout, fetch, and DOM events.
  3. The Callback Queue (Task Queue): Where “completed” background tasks wait to be executed.

2. The Event Loop Algorithm

The Event Loop has one simple job: Monitor the Call Stack and the Callback Queue.

  • If the Call Stack is empty, the Event Loop takes the first task from the Callback Queue and pushes it onto the Call Stack to run it.
  • This cycle repeats forever.

3. Microtasks vs. Macrotasks

Not all tasks are created equal. JavaScript prioritizes certain tasks over others.

A. Macrotasks (Task Queue)

Includes: setTimeout, setInterval, setImmediate, and I/O tasks.

B. Microtasks (Microtask Queue)

Includes: Promises (.then, .catch, .finally) and MutationObserver.

The Golden Rule: The Event Loop will empty the entire Microtask Queue before moving on to the next Macrotask. This is why Promises always run before setTimeout.


4. Understanding Asynchronous Code

When you run a setTimeout, JavaScript doesn’t “wait” for the timer.

  1. It sends the timer to the Web API environment.
  2. The script continues running other code.
  3. When the timer expires, the Web API moves the callback function to the Callback Queue.
  4. The Event Loop waits for the Call Stack to be empty before running that callback.

5. Blocking the Event Loop (The Red Flag)

Since JS is single-threaded, if you run a heavy mathematical calculation or a very long loop, you “block” the Call Stack. The Event Loop cannot check the queues, meaning the browser freezes—you can’t click buttons or scroll.

Example of Blocking Code:

JavaScript

console.log("Start");

// A heavy loop that takes 5 seconds
for (let i = 0; i < 1000000000; i++) {} 

console.log("End"); 
// The browser will be frozen until "End" is printed.

Technical Code Example: The Priority Race

Predict the output of the code below to see if you understand the queue priorities:

JavaScript

console.log("1: Script Start");

setTimeout(() => {
    console.log("2: SetTimeout (Macrotask)");
}, 0);

Promise.resolve().then(() => {
    console.log("3: Promise (Microtask)");
});

console.log("4: Script End");

Correct Output:

  1. 1: Script Start (Synchronous)
  2. 4: Script End (Synchronous)
  3. 3: Promise (Microtask) (Microtasks have priority!)
  4. 2: SetTimeout (Macrotask) (Runs only after Microtasks are clear)

In Simple Words

1. Why This Module Matters

Modern applications must handle:

  • Thousands of users
  • Network requests
  • File I/O
  • Timers
  • UI interactions

All of this happens without blocking the main thread.

The Event Loop is the engine behind non-blocking, asynchronous execution.


2. What Is Concurrency?

Definition

Concurrency is the ability to manage multiple tasks at the same time, even if they are not executed simultaneously.

Concurrency vs Parallelism

ConcurrencyParallelism
Task switchingMultiple cores
Single thread possibleRequires multiple threads
I/O focusedCPU focused

3. Single-Threaded Execution Model

JavaScript (and Node.js) is:

  • Single-threaded
  • Non-blocking
  • Event-driven

Only one call stack, but many tasks are handled via the event loop.


4. Core Components of the Event Loop

4.1 Call Stack

  • Tracks function execution
  • LIFO structure
  • Blocking if long-running tasks exist

4.2 Web APIs / Node APIs

  • Provided by browser or Node runtime
  • Handles async operations:
    • Timers
    • HTTP
    • File I/O
    • DOM events

4.3 Callback Queue (Macrotask Queue)

  • Stores completed async callbacks
  • Examples:
    • setTimeout
    • setInterval
    • I/O callbacks

4.4 Microtask Queue

  • Higher priority queue
  • Always executed before macrotasks

Examples:

  • Promises (then, catch)
  • queueMicrotask
  • MutationObserver

4.5 Event Loop

  • Continuously checks:
    1. Is stack empty?
    2. Run all microtasks
    3. Pick one macrotask
    4. Repeat

5. Execution Order Explained

Priority:

  1. Synchronous code
  2. Microtasks
  3. Macrotasks
  4. Rendering (browser)

6. Promises & the Event Loop

  • Promises resolve into microtasks
  • Faster than timers
  • Can starve macrotasks if misused

7. Async / Await Internals

  • Syntax sugar over Promises
  • Pauses execution without blocking thread
  • Resumes via microtask queue

8. Starvation & Blocking

Event Loop Blocking

  • Heavy computation blocks everything
  • UI freezes
  • Requests stall

Solutions

  • Web Workers
  • Worker Threads
  • Offload CPU tasks

9. Timers in Detail

APIBehavior
setTimeoutExecutes after delay
setIntervalRepeated execution
setImmediate (Node)After I/O
requestAnimationFrameBefore repaint

10. Node.js Event Loop Phases

  1. Timers
  2. I/O callbacks
  3. Idle/prepare
  4. Poll
  5. Check
  6. Close callbacks

Microtasks run between phases.


11. Concurrency Models

Event-Driven Model

  • Non-blocking
  • Callback-based
  • High throughput

Thread-Based Model

  • Multiple threads
  • Shared memory
  • Requires synchronization

12. Workers & Threads

Web Workers

  • Background threads
  • No DOM access
  • Message-based communication

Worker Threads (Node)

  • True parallelism
  • CPU-heavy workloads

13. Race Conditions

  • Order-dependent bugs
  • Shared mutable state
  • Hard to debug

Prevention

  • Immutability
  • Locks
  • Atomic operations

14. Deadlocks & Livelocks

  • Circular waits
  • Resource contention
  • Avoid via timeouts and ordering

15. Synchronization Techniques

  • Mutex
  • Semaphore
  • Message passing
  • Event emitters

16. Backpressure Handling

  • Too many tasks overwhelm system
  • Queues grow infinitely

Solutions

  • Throttling
  • Debouncing
  • Rate limiting

17. Concurrency Patterns

  • Producer–Consumer
  • Pub–Sub
  • Task Queue
  • Worker Pool

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥