Sunday, 9 November 2014

V8, Javascript, Event Loop

This is what i understood form Philip Robert's speech at JSConf EU 2014
V8 is Google's Open Source Javascript Engine. It is written in C++ and is used in Google Chrome.

The Big Picture,




i.e Java runtime, webapi(extra things which the browser provides), event loop and the callback Queue.

Javascript is a single threaded runtime, i.e it has a single call stack (it can execute only one piece of code at a time).
(Note: A call stack is basically a data structure which records where in the program we are.)

Blocking - Essentially, it means code that is slow and therefore preventing execution of statements after it. For example a while loop, which runs for say 100 times. Until the while loop is over , statements after it won't be executed. The browser cannot render anything until there is some process in the call stack.


The solution to blocking - asynchronus callbacks.

Now, the browser is more than the runtime as shown in the picture. It has other components like Web API, event loop which help in concurrency,i.e , executing more than one instruction at a time.


Consider this piece of code 



If we look at the call stack, the callback queue and the event loop together, we see the following picture initially.


When we start the script,we find the picture to be this
When console.log('Hi') is executed,



Now, as we saw before, setTimeOut is a API provided by the browser, so setTimeOut(cb) sets off the timer and is then handled by the browser. So, just after the statement is executed, we find

that is, the setTimeOut is not there in the callstack any more and thus the next console.log() statement is executed and clears off after which the main() clears off (pops off).The browser is handling the setTimeOut. The WebAPI cannot simply push the command back to stack.

Here comes the role of the Event Loop . It looks at the stack and at the queue. If the stack is empty, it pushes the first thing in the queue to the stack where it gets executed.

Note: We use a timer of 0 to setTimeOut when we do not want the statement to be executed until the stack is clear.

setTimeOut is not a guaranteed time of execution. It is the minimum time of execution.



No comments:

Post a Comment