Disclaimer: This article is a mixture of two articles and important points are extracted from both and some new are also added to make it complete
In this article, we will cover the following stuff:
What the heck is the event loop?
How do JS works? V8 engine, JS is single-threaded then how is a callback in JS
What is JS? - A single-threaded non-blocking asynchronous concurrent language
JS - It has a call stack, an event loop, a callback queue, and some other APIs and stuff.
Architecture of Chrome
Let me go through different parts of the chrome (image above)
Heap: Unstructured region of memory
Stack: Represents the single-threaded call stack.
Browser of Web API: They are not part of the JavaScript language itself, rather they are built on top of the core JavaScript language, providing you with extra superpowers to use in your JavaScript code
Go through this below example carefully:-
function main(){
console.log('A');
setTimeout(
function display(){ console.log('B'); }
,0);
console.log('C');
}
main();
// Output
// A
// C
// B
The call to the main function is first pushed into the stack (as a frame). Then the browser pushes the first statement in the main function into the stack which is console.log(āAā). This statement is executed and upon completion, that frame is popped out. Alphabet A is displayed in the console.
The next statement (setTimeout() with callback exec() and 0ms wait time) is pushed into the call stack and execution starts. setTimeout function uses a Browser API to delay a callback to the provided function. The frame (with setTimeout) is then popped out once the handover to the browser is complete (for the timer).
console.log(āCā) is pushed to the stack while the timer runs in the browser for the callback to the exec() function. In this particular case, as the delay provided was 0ms, the callback will be added to the message queue as soon as the browser receives it (ideally).
After the execution of the last statement in the main function, the main() frame is popped out of the call stack, thereby making it empty. For the browser to push any message from the queue to the call stack, the call stack has to be empty first. That is why even though the delay provided in the setTimeout() was 0 seconds, the callback to exec() has to wait till the execution of all the frames in the call stack is complete.
Now the callback exec() is pushed into the call stack and executed. The alphabet C is displayed on the console. This is the event loop of javascript.
Another Example:-
function init() {
var link = document.getElementById("foo");
link.addEventListener("click", function changeColor() {
this.style.color = "burlywood";
});
}
init();
%[https://www.youtube.com/watch?v=8aGhZQkoFbQ]
Thanks for reading follow the Interview JS series for more core concepts of JavaScript.
Top comments (1)
just yesterday i get interviewed by company about this one and i can't answered lol but i hope in the next interview i can answer this aamiin