Question

Does JSVM run just in one thread? I am wondering how the JavaScript function executing inside the VM. The source code below is interesting:

// include jQuery as $
function test() {
  $.ajax({url:"xxx.com"})
    .success(function() {alert("success 1");})
    .fail(function() {alert("fail 1");});
  $.ajax({url:"yyy.com"})
    .success(function() {alert("success 2");})
    .fail(function() {alert("fail 2");});
  while(true);
}

It will make die loop at the "while" line and never pop up any alert dialog to show neither "success" nor "fail". We know inside the $.ajax, the VM creates XMLHttpRequest and sends a HTTP request. After sending out two requests, it meets the "while" line. Thus I image that the JSVM:

1) can handle only function call at one time. (function is atomic)

2) follow the rule: first comes, first served.

Does my idea right? Does anyone can explain the internal implementation of JSVM?

More specific, If using AngularJS to develop a front end app, we would like to do something and then immediately record a log to remote server in form submit event like ng-submit.

function ngSubmitTest() {
  doA();
  recordA(ajax, remoteServer); // must after doA()
}

If recordA uses AJAX, we should ensure recordA is complete before ng-submit redirect the page meanwhile kill the old page and also the VM (if the old page is killed, the recordA may not complete). One solution is doing AJAX with async=false. And I wonder if there is any other solutions?

Thanks.

Was it helpful?

Solution

The implementation of JS depends on the context you're runing it.

Each browser has it's own implementantion, and they can do whatever they want as long as they follow the language specification.

It shouldn't bother you if it runs on one or multiple threads, but you can be sure JavaScript is not a "threaded" language, it works with an event loop flow, in which an event is fired, and consecutive functions are fired after that, until there is nothing more to call. This is the reason why it's pretty hard to block the UI in JavaScript if you're writing "good" code.

A good example on how this works, and the diferences betwen event loops and classic threading, is node.js, i'll give you a example:

Supose you're listening for a request on a server, and 2 seconds after the request arrives you'll send a message. Now let's supose you duplicate that listener, and both listeners do the same thing. If you request the server, you'll get the two messages at the same time, 2 seconds after the request is made, instead of one message on 2 seconds, and the other one on 4 seconds. That means both listeners are runing at the same time, instead of following a linear execution as most systems do.

Node runs Chrome's V8 if you're wondering, it's a very professional JS interpreter and it was a breakthorugh when it came out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top