Mark As Completed Discussion

How does the JS Runtime work?

There are three main concepts to discuss when talking about JS Runtime and how it works. Let's take a look at each of them in more detail:

1. Web APIs

There are a large number of APIs available in modern browsers that allow us to do a wide variety of things. Some of the most common categories of JS APIs let us:

  • Manipulate documents - The DOM API allows developers to manipulate HTML and CSS, letting us create, change and even remove HTML and dynamically apply styles to web pages.
  • Draw and manipulate graphics- The Canvas API and the Web Graphics Library API allow to programmatically update pixel data contained in a <canvas> element.
  • Fetch data from a server - The Fetch API provides an interface for fetching resources across the network by using generic definitions of the Request and Response objects.

Features like event listeners, timing functions and AJAX requests all sit in the Web APIs container until an action gets triggered. When a request finishes receiving its data, a timer reaches its set time or a click happens and this triggers a callback function to be sent to the Callback queue.

2. Callback queue

The Callback queue stores the callback functions sent from the Web APIs in the order in which they were added. This queue is a data structure that runs in FIFO order.

Callback functions will sit in the queue until the call stack is empty, they are then moved into the stack by the event loop.

How does the JS Runtime work?

3. Event loop

The Event loop constantly monitors the state of the call stack and the callback queue. If the stack is empty it will grab a callback from the callback queue and put it onto the call stack, scheduling it for execution.

By pushing callbacks from the Web APIs to the callback queue, the event loop can constantly add those callbacks to the call stack, which makes us think of JavaScript as being able to run asynchronously.