Understanding the JS Event Loop

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:

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

Now that I do not understand why they all do not work together? is it because the server side can only process one request at a time or rotates with js event loop?

+4
source share
2 answers

What this experiment shows is that the server processes requests one by one, and not in parallel. Why it is not immediately visible.

Perhaps the server is single-threaded. Another possibility is that queries require a shared (locked) resource, such as a user session or a locked database table.

+2

. ( ), javascript . Javascript anyways , .

0

Source: https://habr.com/ru/post/1606422/


All Articles