The letters 'JS' within a square

JavaScript: V8 Engine

How the V8 engine works

The letters 'JS' within a square

JavaScript: V8 Engine

How the V8 engine works

V8 Engine

Source Code

Memory Heap

Call Stack

Console

Event Loop

Callback Queue

Web API

V8 Engine

Source Code

Memory Heap

Call Stack

Console

Event Loop

Callback Queue

Web API

JavaScript is synchronous. It can only execute 1 task at a time.

If an invoked function takes a long time to return, like fetching data from a server, the browser can’t do anything else until it completes. Execution will be blocked & the browser will be unresponsive.

Because JavaScript is an event-driven language. It is possible to support non-blocking operations. Such as asynchronous callbacks.

Asynchronous means the engine can execute tasks while waiting for another task to complete.

The browser provides Web APIs such as the DOM, setTimeout & fetch.

When a fetch request is made, instead of waiting for it to complete, its callback gets added to the Web API. The browser then sets up to listen for the response from the network.

The fetch frame then gets popped off the stack & the engine continues execution.

When the network request is received, the callback is passed to the Callback Queue.

The Callback Queue is an array with 2 operations: push (adds an element to the end) & shift (removes an element from the front). “First In, First Out” protocol (FIFO).

The Event Loop connects the Callback Queue with the Call Stack.

When the Call Stack becomes empty & there are items in the Callback Queue, the Event Loop will push the 1st to the Call Stack & it will be executed.

/index.js

function callback() {
    console.log("callback invoked")
}

function func1() {
    console.log("func1 invoked")
}

fetch("https://...")
    .then(callback)

func1()
                    
An arrow pointing right
2 arrows pointing left & right
main()
fetch("https://...")
callback()
func1()
> func1 invoked > callback invoked >
callback()
callback()

Increase browser width to view this page.