How the V8 engine works
How the V8 engine works
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.
function callback() {
console.log("callback invoked")
}
function func1() {
console.log("func1 invoked")
}
fetch("https://...")
.then(callback)
func1()
main()
fetch("https://...")
callback()
func1()
callback()
callback()
Increase browser width to view this page.