Browser and JavaScript interaction

Browser and JavaScript interaction

Things like waiting for an event to occur or rendering an HTML page execute in the browser's native context. Initially, the browser waits for an event to occur, for example, the user clicks a button or enters text in an put field. When an event is raised, the browser responds to the event by checking if there is any associated event handler code written in JavaScript. If there is any such code, the execution enters the JavaScript execution context and executes the code as response to the event. In the process, it may update the DOM. Note that all the JavaScript code is executed in the JavaScript execution context. After the execution is complete, it gets back to the native browser context where the browser observes the changes made to the DOM, re-renders the page based on DOM changes, and returns to waiting for more events. When code executes in the JavaScript runtime, note that it doesn't suspend the browser runtime from accepting user input events.

A JavaScript engine is a virtual machine (VM) which interprets and executes JavaScript. There are actually several JavaScript engines available like V8, Chakra, Spider Monkey but by far the most popular version is Google Chrome's V8 engine. JavaScript VM is single threaded meaning that it exists in a single OS process, and consumes a single thread. Only one task can be executed at a time, that is to say that there is one JavaScript execution context or 'thread'. 

When your inline script, timeout, or event listener is entered, you remain completely in control until you return from the end of your block or function. This guarantees atomic and consistent behavior between all callbacks.

Java, for example, is multi-threaded and it witnesses race conditions. A race condition occurs when two or more threads can access shared data and they try to modify it at the same time. Improper usage of concurrency can lead to side-effects like deadlocks,  resource starvation. Unlike Java, there are no race conditions in JavaScript. Any individual thread of execution will run to completion before the next one starts. It is impossible for users to get the deadlock like situations. Also, you do not need write any complex syntax to handle concurrency.

However, the major disadvantage is that if your JavaScript code is doing CPU intensive computation, the entire browser's user interface is frozen while a JavaScript thread is running. Another disadvantage is that it just makes use of only a single CPU core at a time regardless of the fact that there might be multiple CPU cores in your machine. But if there are multiple browser instances, note that, each instance can use a separate CPU core. The code written in a language that supports multi-threading makes use of separate CPU cores as 'threads'.

For Part 2, click this link: JavaScript runtime: Call Stack and Event Queue - Part 2