4

I am trying to understand the js event loop. This is my js code:

var start = new Date().getTime();
var url = "/WebForm1.aspx/Test1";
$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log('Test1, elapsed: ' + (new Date().getTime() - start) + 'ms');
    },
});

url = "/WebForm1.aspx/Test2";
$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log('Test2, elapsed: ' + (new Date().getTime() - start) + 'ms');
    },
});

url = "/WebForm1.aspx/Test3";
$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log('Test3, elapsed: ' + (new Date().getTime() - start) + 'ms');
    },
});

This is my server side code:

[WebMethod]
public static void Test1()
{
    System.Threading.Thread.Sleep(1500);
}

[WebMethod]
public static void Test2()
{
    System.Threading.Thread.Sleep(2000);
}

[WebMethod]
public static void Test3()
{
    System.Threading.Thread.Sleep(3000);
}

Now the result is :

Test1, elapsed: 1542ms
Test3, elapsed: 4578ms
Test2, elapsed: 6636ms

Now what i dont understand is, why doesnt they all execute together? is it because the server side can process only one request at a time, or does it revolves with the js event loop?

omriman12
  • 1,644
  • 7
  • 25
  • 48

2 Answers2

2

What this experiment shows is that the server handles the requests one-by-one, instead of in parallel. Why this is is not immediately apparent.

It's possible that the server is single threaded. Another possibility is that the requests require a shared (locked) resource for instance the user session or a locked database table.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
0

The two arguments are correct. Your server can handle just one request at a time (with the same origin), and javascript has to wait for the server. Javascript anyways will execute one response at time, because it's single threaded.

Miguel Lattuada
  • 5,327
  • 4
  • 31
  • 44
  • _Your server can handle just one request at a time_ - **proof?** _Javascript anyways will execute one request at time_ - **no** (unless asynch=false is passed, which it is not) – Halcyon Sep 08 '15 at 14:25
  • Because is how asp.net works http://stackoverflow.com/questions/1735107/can-a-single-asp-net-user-make-more-than-one-request-at-a-time-if-the-session-is , and you are right with javascript, it could execute n requests, but responses will be handled one by one. It's more about server side. – Miguel Lattuada Sep 08 '15 at 14:29
  • This has nothing to do with asp.net, but with how sessions work; or locked resource in general. You see the same behaviour in PHP. If you close the session before you `sleep()`, the other requests wont need to wait. – Halcyon Sep 08 '15 at 14:31