Back to Blog

Demystifying JavaScript Runtime Environment: Web API, Task Queue, and Event Loop

JavaScript's inner workings can be complex and fascinating. In this article, we'll delve deeper into the JavaScript runtime environment, exploring asynchronous code execution, and how the browser provides essential features for web development.

Demystifying JavaScript Runtime Environment: Web API, Task Queue, and Event Loop

In one of the previous articles, we delved into the fundamentals of the JavaScript engine, covering essential language features such as calculations and loops. However, the world of JavaScript is far more intricate, especially when it comes to handling asynchronous code and utilizing browser-provided objects. To navigate this complexity, we'll dive into the JavaScript runtime environment, which comprises Web API, Task Queue, and the Event Loop.

Browser Provides Features Beyond the JavaScript Engine

The Web API, also known as the Browser API, is an essential part of the runtime environment provided by the browser. It's separate from the JavaScript engine but allows you to interact with browser features using JavaScript. Some aspects of the Web API include its facilitation of concurrent operations external to the JavaScript interpreter, despite JavaScript's inherent single-threaded nature.

When a function call involves asynchronous operations, like making an HTTP request, setTimeout, or handling events, the JavaScript engine delegates the handling of these operations to the browser's corresponding API (e.g., XMLHttpRequest or Fetch API) instead of blocking the call stack and waiting for the operation to complete (which would freeze the browser interface). Along with delegating the task, the engine also registers a callback function to be executed once the operation completes or an event occurs. Upon completion, when a timer reaches its designated time, or upon a user's click event, the corresponding callback is typically dispatched to the Task Queue.

Examples of Web APIs

Document Manipulation: Utilizing the DOM (Document Object Model) for interactive web content manipulation and organization.

  • Server Data Retrieval: Employing the Fetch API to seamlessly retrieve data from servers.
  • Timer Functions: Utilizing APIs to manage and trigger time-based operations within web applications.
  • Graphics Drawing and Manipulation: Leveraging the Canvas API and WebGL API for graphical content creation and manipulation on web platforms.
  • Audio and Video Handling: Utilizing APIs like the Web Audio API and WebRTC API for audio/video streaming and manipulation.
  • Device-Related Functions: Utilizing the Geolocation API to access location-based services on web applications.
  • Client-Side Storage: Leveraging Web Storage API and IndexedDB API for efficient client-side data storage and retrieval within browsers.

In Node.js, there are no browser-provided Web APIs. Instead, Node.js presents a distinct set of APIs unrelated to browsers. These encompass functionalities for file system operations, network communication, and more. As Node.js is primarily utilized for server-side JavaScript applications, its APIs are specifically designed for that environment.

The Task Queue functions as a message queue where each message corresponds to an associated function for execution. Here are its key characteristics:

  • Messages follow a First-In, First-Out (FIFO) processing order.
  • It enables the execution of code after the completion of API calls.
  • Within the Event Loop, once the call stack is clear, the runtime proceeds to process the oldest message in the queue by invoking its functions and adding them to the Call Stack.
  • Function execution continues until the Call Stack is empty, after which the next message in the queue is processed.

The Task Queue is sometimes referred to as the "Event Queue" or "Callback Queue." Tasks are added to this queue when an event triggers a callback or when a specified timeout/interval expires.

Microtask queue

The Microtask Queue is similar to the task queue but has higher priority. It handles Microtask callbacks, including promise handlers and mutation observers.

Microtasks consist of concise functions executed after the parent function or program finishes, but only when the Call Stack is clear. Some essential aspects of microtasks include:

  • Microtasks have the capability to enqueue additional microtasks, and these subsequently queued microtasks execute before the next task initiates, all within the same event loop iteration.
  • They are designed to handle actions that require immediate execution following the current script, such as responding to a series of actions or implementing asynchronous functionality without incurring the overhead of a completely new task.

The Event Loop stands as a crucial element within the JavaScript runtime environment, functioning in the following manner:

  • Continuously monitoring the status of the call stack to determine if it's empty.
  • Upon encountering an empty call stack, all pending Microtasks from the Microtask Queue are introduced into the call stack.
  • When both the call stack and Microtask Queue are devoid of tasks, the event loop proceeds to dequeue tasks from the Task Queue and execute them.
  • Ensuring the prevention of a "starved event loop" remains pivotal for maintaining seamless JavaScript execution.
1// Event loop algorithm
20.  Dequeue and execute the oldest task from the task queue.
31.  Execute all Microtasks:
4    - While the microtask queue is not empty:
5      - Dequeue and execute the oldest microtask.
62.  Render any pending changes.
73.  If the task queue is empty, wait for a new task.
84.  Go back to step 1.

In Node.js, the Event Loop shares similarities with the browser environment, yet it diverges in its handling of I/O operations and event-driven code. Node.js leverages a unique array of modules like fs for file system operations and http for constructing HTTP servers, pivotal to its event-driven architecture while maintaining the core concepts of the Event Loop and Task Queue.

Exploring how JavaScript works behind the scenes revealed a bunch of moving parts. There's the Web API that helps JavaScript do more than it could on its own, handling tasks like fetching data or dealing with graphics. Then there's the Task Queue and Microtask Queue, kind of like waiting lines for different jobs. The Event Loop is like a supervisor, making sure tasks get done in the right order without things getting stuck. In a different world called Node.js, it's similar but has its own special tools for handling stuff. Understanding how all this works helps folks build cooler and faster websites and apps that keep up with the ever-changing web.

Contact us today...

to discuss your web development project and discover how our team can help you achieve your goals.

Tell us about your project

Empower your vision, partner with us today

Author photo
Jakub Czapski
Founding Partner at Blazity
To best serve you, let's get to know your requirements first. Tell us about your project, and we'll arrange a free consultation call to discuss how we can help.

Trusted by:

Trusted by logoTrusted by logoTrusted by logoTrusted by logo
Do you need an NDA first?