SetTimeout and SetInterval of JavaScript asynchronous programming

Source: Internet
Author: User
Tags setinterval

http://www.cnblogs.com/tugenhua0707/

In the case of asynchronous programming, I will mainly from the following three aspects to summarize the asynchronous programming ( Note: Special explanation: is summed up, I am also a rookie, so the summary is not good, please Daniel a lot of forgiveness! )

1. settimeout and SetInterval analyze the fundamentals in Detail.

Next this blog will summarize settimeout and setinterval basic point, for the above three points will be divided into three blog to summarize, for the people who know the above three points, but not very understanding of the overall knowledge points of the yards of the farmers, no relationship, we can slowly learn, to understand, Or I summarize not comprehensive or bad place can leave a message, learning is to interact, only to Improve. of course, for those knowledge daniel, can also look at, if I summarize not good words, can also mention advice, I can also learn more!

Before studying settimeout and setinterval, we can take a look at a small demo, in fact, the summary and research is to do more demo, because some things we look very simple, really do not do so the same time. such as the Following:

for (var i = 1; I <= 3; i++) {

SetTimeout (function () {

Console.log (i);

},100);

}

If the JavaScript language is not very familiar, many people will take it for granted that the for loop will be printed separately. But that is not the case, it will output 3 times 4. To understand why print three times 4, we first understand settimeout this function, many people will think that the above settimeout means that, in 100 milliseconds after the execution of SetTimeout callback function, in fact, this understanding is wrong, In fact settimeout and setinterval really mean the following:

    1. SetTimeout: after the specified number of milliseconds, the functions processed by the timer task are added to the end of the queue for Execution.
    2. Setinterval: adds a timer task handler to the end of the queue at the specified period (in milliseconds).

SetTimeout and SetInterval are both asynchronous, so we can now understand why the above loop is always 4? In fact, when the call settimeout, there will be a delay event queued, and then settimeout call after the line of code to run, and then the next line of code, until there is no code, JavaScript virtual machine will ask, the queue is there? If at least one event in the queue is appropriate for a trigger, such as the settimeout function above, the settimeout function is Called. So the above code first for the loop, the loop ends, and i = = 4 is incremented until the i<=3 is no longer satisfied. So I printed 3 of the 4.

Let's take a look at the following function, as Follows:

SetTimeout (function () {

Console.log ("print me, I was executed asynchronously");

},100);

Console.log ("i'm New here, I want to do it first");

The result is: "i'm new here, i'll do it first," and then print "print me, I'm asynchronous" code.

Two: understand JavaScript threads.

The JavaScript engine is single-threaded, and the browser runs at all times and only one thread is Running.

So how does a single thread handle these timers and corresponding browser events with the browser kernel?

The browser kernel allows multiple threads to execute asynchronously, which are synchronized with each other under the control of the kernel, such as a browser with at least 3 threads, a JavaScript engine thread, an interface rendering thread, a browser event-triggering thread, and, among other things, some executed threads. such as HTTP request threads, These asynchronous threads produce different asynchronous Events.

Interface Rendering Thread:

The thread is responsible for rendering the browser HTML interface element, which executes when the interface needs to be redrawn or because of an operation that causes reflux (reflow), which is mutually exclusive to the JavaScript engine thread, because the JavaScript engine runs the script, Browser rendering threads are out of hang state, for example, we are common in the page head tag is not recommended to put JS on the head of the reason, hope to put JS in the tail or use asynchronous loading Operations. As a result, updates to the interface are performed in the script, such as dynamically adding nodes or deleting nodes, which put these events in the queue, and when the JavaScript engine is idle, the opportunity to Render.

Browser Event Trigger Thread:

When a user clicks a DOM element with an attached click event handler, a single click event is queued, but the click event handler waits until all currently running code has ended before it Executes.

such as the following a small demo, we usually write code, especially with the trial JavaScript writing tab switch, often encounter the following code, such as click on an Li tag, want to switch to the corresponding Content. Click on the event demo BELOW. I use jquery here to demonstrate the following:

The HTML code is structured as Follows:

<li class= "container" > click I 1</li >

< li class= "container" > click I 2</li >

< li class= "container" > click I 3</li >

JS as Follows:

var lists = $ (". container");

for (var i = 0, Ilen = lists.length; I < ilen; i++) {

$ (lists[i]). bind (' Click ', function () {

Console.log (i); Printing 3

});

}

The above code click, print out 3 (not 0,1,2), The principle is the same as Above.

Timed Trigger Thread:

The timer counters mentioned here are not counted by the JavaScript engine, because the JavaScript engine is single-threaded and if it is not counted when it is plugged in, it must rely on external timing and trigger timing, so timed events in the queue are also asynchronous Events.

Three: Understanding SetTimeout and SetInterval Asynchronous events:

Javascript's most basic asynchronous function is that settimeout and setinterval,settimeout execute the corresponding function after a certain amount of time, which takes a callback function and a millisecond time, such as the Following:

Console.log ("a");

SetTimeout (function () {

Console.log ("c")

}, 500);

SetTimeout (function () {

Console.log ("d")

}, 500);

SetTimeout (function () {

Console.log ("e")

}, 500);

Console.log ("b");

The console outputs "a", "b", and then "c", "d", and "e" after about 500 milliseconds.

But if I change the delay time of the first settimeout a little bit or change it to 600 milliseconds, then the print out is a,b,d,e,c. You may have heard the word event loop, which is used to describe how the queue works. When the asynchronous function executes, The callback function is pressed into the queue, and the JavaScript engine does not start out of the event loop until the asynchronous function is executed, which means that JavaScript is not multithreaded, and that the event loop is a first-in (fifo) queue, This means that callbacks are executed in the order in which they were queued (in the same case. ), but if the delay time is not the same, then it will not, as the above-mentioned in the case of the timing of the number of milliseconds to change the output of the Difference.

Four: types of asynchronous functions

The asynchronous functions provided in the JavaScript environment are divided into 2 main categories: I/O functions and timing functions.

We all know that creating nodejs is not about running JavaScript on the server, but because the JavaScript language can perfectly implement non-clogging i/o. For example, A typical Ajax request, the following code:

var url = "http://localhost/setTimeout/index2.php";

var xhr=new xmlhttprequest;

Xhr.open ("GET", "http://localhost/setTimeout/index2.php", true);

Xhr.send ();

Xhr.onreadystatechange=function () {

If (xhr.readystate<4) return;

Alert (xhr.responsetext);

};

Alert ("ajax is not finished Yet?") ");

Run the results first "ajax is not finished yet?" ", after executing the callback function for Onreadystatechange. After you execute the Send method in an AJAX function, bind the event instead of binding the event first, and then send?

In fact, the XHR object uses other threads, there are some cross-thread communication issues, the need to use a delegate when accessing data across threads, Otherwise there will be data conflicts, so-called delegation is actually a thread to another thread to send messages, however, the XHR thread wants to trigger the onreadystatechange event of the main thread XHR object and the main thread is currently busy, it is in the process of initializing the message, and only when the initialization message is idle does the child thread delegate Processing. When the initialization message is idle, it means that the onreadystatechange event is bound, so the subsequent code execution will always be faster than the XHR thread Execution. therefore, The following Alert dialog box is executed before the onReadyStateChange event is Executed. Of course AJAX requests the third parameter we can set to false, synchronous request, generally or asynchronous request good, but in order to deal with some special requirements, you can also set the synchronization request (note: the synchronization request will clog the browser load, so if the requested data is very large, consider the asynchronous request.) ), such as some common requirements, after sending an AJAX request, to open a new window such a requirement, we all know that if the asynchronous request Chrome and Firefox will be intercepted directly, but if I set a synchronization request can be implemented after sending Ajax requests, and then open a new window.

We've seen that async functions are great for I/O operations, but we now want a function to run at some point in the future or an animated function to animate at some point in the Future. This is when we think of the settimeout and setinterval functions in Javascript. however, settimeout and SetInterval have the following defects:

    1. When the same JavaScript process runs code, no JavaScript timer function can make the code run, the following demo test:

var start = new Date;

Sttimeout (function () {

var end = new Date;

Console.log ("time:", end-start, ' Ms ');

},500);

While (new Date-start < 1000) {

}

Want to print out the above console.log, in the browser has been refreshed see, the first 1020ms, the second 1029ms, anyway the result has been more than 1s, that is, after the function if the execution time is very long, then the settimeout code will never Execute.

2. SetInterval According to the HTML specification: within one hours delay 4-5ms such a delay. Which means using this timing is not very precise.

SetTimeout and SetInterval of JavaScript asynchronous programming

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.