Re-recognize settimeout and Asynchronization of javascript

Source: Internet
Author: User
I saw a JavaScript question (setTimeout) from QLeelulu tonight. I thought about it a little bit. It was hard to guess it and I happened to say the correct answer. But why? I am not quite clear at the moment. I feel like it is caused by an endless loop. Then I read the comments below and found that SyntaxHighlight was returned on the fifth and sixth floors.

I saw a JavaScript question (setTimeout) from QLeelulu tonight. I thought about it a little bit. It was hard to guess it and I happened to say the correct answer. But why? I am not quite clear at the moment. I feel like it is caused by an endless loop. Then I read the comments below and found that the answers on the 5th and 6th floors are reasonable. The main meaning is that the javascript engine is executed in a single thread. When the while loop is executed, the functions in settimeout have no chance to execute at all, so that while is always true, resulting in an endless loop. However, it was not very practical to look at it. At last, I tried two experiments by myself:

1. Simple settimeout

SetTimeout (function () {while (true) {}}, 1000 );
SetTimeout (function () {alert (end 2) ;},2000 );
SetTimeout (function () {alert (end1) ;}, 100 );
Alert (end );
The execution result is 'end' 'end 1', And the browser is suspended, that is, 'end 2' is not displayed '. That is to say, the execution in the first settimeout is an endless loop, which directly causes the function to be blocked in the second settimeout that is theoretically executed one second later than it, this is inconsistent with the asynchronous function multithreading that we usually understand.

2. ajax request callback

Next, let's test the ajax asynchronous request calling through xmlhttprequest. The main code is as follows:

Var xmlReq = createXMLHTTP (); // create an xmlhttprequest object
Function testAsynRequest (){
Var url = "/AsyncHandler. ashx? Action = ajax ";
XmlReq. open ("post", url, true );
XmlReq. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
XmlReq. onreadystatechange = function (){
If (xmlReq. readyState = 4 ){
If (xmlReq. status = 200 ){
Var jsonData = eval (+ xmlReq. responseText + ));
Alert (jsonData. message );
}
Else if (xmlReq. status = 404 ){
Alert ("Requested URL is not found .");
} Else if (xmlReq. status = 403 ){
Alert ("Access denied .");
} Else {
Alert ("status is" + xmlReq. status );
}
}
};
XmlReq. send (null );
}
TestAsynRequest (); // call the callback function after 1 second

While (true ){

}
Implement simple output on the server:

Private void ProcessAjaxRequest (HttpContext context)
{
String action = context. Request ["ajax"];
Thread. Sleep (1000); // wait for 1 second
String jsonObject = "{" message ":" "+ action + ""}";
Context. Response. Write (jsonObject );
}
Theoretically, if the asynchronous callback function of an ajax request is in a separate thread, the callback function will be executed smoothly without being blocked by other threads, that is, one second later, the callback execution pops up 'ajax ', but this is not the case. The callback function cannot be executed because the browser crashes again because of an endless loop.

Conclusion: based on the practice, we can conclude that the javascript engine is indeed a single thread processing its task queue (can it be understood as a queue composed of common functions and callback functions ?) . Asynchronous programming in javascript is largely a blind way. The single-threaded engine implements multi-threaded programming, if you want to implement operations such as resource synchronization and mutex (such as multi-threading in C # and Java languages), I feel that the implementation cannot be easily guaranteed.

Supplement: How to Implement javascript sleep? Find a javascript sleep in stackoverflow and try it. The result is yes, but the cpu usage is very high during execution. It is really better to set timeout directly.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.