Event Loop in Javascript - What, Why and How
Everyone knows that javascript is single threaded. But is it guaranteed? - If you answer to this as YES then you might want to read on as there is a concept of event loop in javascript which will change your view (No, it does not make javascript multi-threaded). Then what it is? - Let's read on...
First things first - Why should I even care about event loop?
Consider the following code snippet
What most of us would have expected would be to logging of "Binary" followed by "Singh" followed by "Blog" because that is how javascript works. But to understand the above behavior of JavaScript we need to take a look at the concept of the event loop.
Let's start by learning how JavaScript runs in your chrome browser
Consider the following code snippet
function main(){ console.log('Binary'); setTimeout( function display(){ console.log('Singh'); } ,0); console.log('Blog'); } main(); // Output // Binary // Blog // Singh
What most of us would have expected would be to logging of "Binary" followed by "Singh" followed by "Blog" because that is how javascript works. But to understand the above behavior of JavaScript we need to take a look at the concept of the event loop.
Let's start by learning how JavaScript runs in your chrome browser
V8 is a Chrome's Javascript Engine which is responsible for running all your javascript code. It compiles and executes JavaScript source code, handles memory allocation for objects, and garbage collects objects it no longer needs. The image below shows a simplified view of what Javascript's runtime of v8 is
Comments
Post a Comment