SetTimeout and asynchronous thinking in JavaScript

Source: Internet
Author: User
Tags sleep javascript settimeout

The following code, how long will the ' end ' pop up? Why?

The code is as follows Copy Code

var t = true;
settimeout (function () {t = false;}, 1000);
while (t) {}
Alert (' End ');

This is an implementation that was previously thought of when you could not implement a blocking JavaScript thread (that is, to implement the Sleep method).
It's simple, isn't it?
Is it?

Re-recognize JavaScript settimeout and Asynchrony
Tonight I saw a JavaScript question (settimeout) of Qleelulu, a little thought, and finally took a guess at the answer. But what is the reason? I also said that I was not very clear, anyway, the feeling is a death cycle caused. And then look at the comments below the article, found on the 5 floor (typical death cycle ...) JS is single-threaded, while inside the settimeout function is not a chance to execute. And the 6 floor (settimeout just hangs a timed task, but JS itself is single-threaded, While there must have died. The answer is very reasonable, the main meaning is that the JavaScript engine is single-threaded execution, while loop where the execution, settimeout inside the function does not have the opportunity to execute, so while there is always true, resulting in a dead loop. But the simple look is still not steadfast, finally play the practical spirit, do-it-yourself did two experiments:
1. Simple settimeout

The code is as follows Copy Code

settimeout (function () {while (true) {}},1000);
settimeout (function () {alert (' End 2 ');},2000);
settimeout (function () {alert (' End 1 ');},100);
Alert (' End ');

The result of the execution is to eject ' end ' 1′, and then the browser to suspend animation, is not to eject the 2′. That is, the first settimeout execution is a dead loop, which leads directly to a function in the second settimeout that is theoretically more than a second later, and this is not consistent with the asynchronous function multithreading we normally understand.

2. Ajax Request Callback
Then we'll test the Ajax asynchronous request invocation via XMLHttpRequest, the main code is as follows:

The code is as follows Copy Code

var xmlreq = Createxmlhttp ();//Create a 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 ();//1 seconds after calling callback function
while (true) {}

Implement simple output on the server side:

The code is as follows Copy Code

private void Processajaxrequest (HttpContext context) {
String action = context. Request["Ajax"];
Thread.Sleep (1000);//wait 1 seconds
String jsonobject = "{" Message ":" "+ Action +" "}";
Context. Response.Write (Jsonobject);
}

Theoretically, if the Ajax asynchronous request, its asynchronous callback function is in a separate thread, then the callback function must not be "blocked" by other threads to execute smoothly, that is, 1 seconds later, it callback execution pop-up ' Ajax ', but this is not the case, the callback function can not be executed, Because the browser again because of dead loop suspended animation.

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.