Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

The JavaScript Concurrency Model

Topic 2JavaScript Part 2 (Async JS)

The JavaScript Concurrency Model

Introduction

The JavaScript concurrency model consists of several key components that work together to enable asynchronous execution: the Call Stack, Web APIs, Callback Queue, and Event Loop.

Key Concepts and Definitions

Call Stack

Executes functions in a last in, first out (LIFO) manner. Synchronous code is pushed and popped directly on the call stack. Asynchronous tasks are deferred to Web APIs or other threads.

Example:

function greet() {
  console.log('Hello!');
}
greet(); // "Hello!" is executed immediately.

Web APIs

Provided by the browser or Node.js, handle asynchronous tasks like setTimeout, fetch, and DOM events. When a task completes, its callback is pushed into the callback queue.

Callback Queue

Holds completed asynchronous tasks. Tasks are moved to the call stack when it is empty.

Event Loop

Continuously checks if the call stack is empty. If the call stack is empty, the event loop moves the next task from the callback queue to the call stack for execution. The event loop is a mechanism in JavaScript that continuously monitors the call stack and the callback/microtask queues. It ensures that tasks from the callback queue (macrotasks) or microtask queue are pushed onto the call stack when it is empty, enabling non-blocking asynchronous execution.

Step-by-Step Explanation

Execution Flow:

  • •Synchronous code executes directly on the call stack.
  • •Asynchronous tasks are sent to Web APIs.
  • •When Web API tasks complete, callbacks go to the callback queue.
  • •Event loop moves callbacks from queue to call stack when stack is empty.

Interview guide discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment