SetTimeout and SetInterval of JavaScript asynchronous programming
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:
- SetTimeout: After the specified number of milliseconds, the functions processed by the timer task are added to the end of the queue for execution.
- 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:
- 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. That means using this timing is not very precise.
SetTimeout and SetInterval Analysis of JavaScript Asynchronous Programming (I.)