function A () {var n = 0; for (var i=1;i<10000000;i++) {n=i+n;} document.getElementById (' A1 '). Value=n;} function B () {document.getElementById ("A2"). value=22222} A (); b ();
Look at the above two functions, in the execution of the result of writing two input, it must be a function completed, and then execute the B function, this is a single thread queue. How to execute these two functions asynchronously, that is, a slow execution, and b do it directly without waiting for the end of a.
# #setTimeout Mysterious function.
This function is the key to Asynchrony, look at the code:
Function C (fuc) {settimeout (function () {a (); fuc;},1000);} c (b ());
Where the A function and the B function are executed with settimeout (), an asynchronous execution is generated and the B function does not wait for a execution to complete.
Small problem with settimeout function:
The waiting time is not accurate, there will be delay
Try.. Catch does not capture error messages
This article summarizes the 4 methods of "Asynchronous mode" programming, and understands that they allow you to write JavaScript programs that are more structured, better performing, and easier to maintain.
One, callback function
This is the most basic method of asynchronous programming.
It is assumed that there are two functions F1 and F2, which wait for the results of the former's execution.
F1 ();
F2 ();
If F1 is a time-consuming task, consider rewriting F1 to write F2 as a F1 callback function.
Function F1 (callback) {
settimeout (function () {
F1 's Task code
Callback ();
}, 1000);
}
The execution code becomes the following:
F1 (F2);
In this way, we turn the synchronization operation into an asynchronous operation, and F1 does not jam the program running, which is equivalent to executing the main logic of the program first, delaying the execution of the time-consuming operation.
The advantage of the callback function is simplicity, ease of understanding and deployment, which is not conducive to code reading and maintenance, is highly coupled between parts (coupling), the process is messy, and each task can only specify one callback function.
Second, event monitoring
Another idea is to use event-driven mode. The execution of a task does not depend on the order of the Code, but on whether an event occurs.
Take F1 and F2 for example. First, bind an event to the F1 (the jquery notation used here).
F1.on (' Done ', F2);
The above line of code means that when the F1 occurs, the F2 is executed. Then, rewrite the F1:
Function F1 () {
settimeout (function () {
F1 's Task code
F1.trigger (' done ');
}, 1000);
}
F1.trigger (' Done ') indicates that after the execution is complete, the completed event is triggered immediately to begin execution of the F2.
The advantage of this approach is that it is relatively easy to understand, can bind multiple events, each event can specify multiple callback functions, and can be "decoupled" (decoupling), facilitate the implementation of modularity. The disadvantage is that the entire program becomes an event-driven type, and the running process becomes very unclear.
Third, publish/Subscribe
The "events" in the previous section can be fully understood as "signals."
We assume that there is a "signal center" in which a task is executed to "release" a signal to the signal center, and other tasks can "subscribe" to the Signal Center (subscribe) to know when they can begin to perform publish. This is called "Publish/Subscribe Mode" (Publish-subscribe pattern), also known as "Observer Mode" (Observer patterns).
This pattern is implemented in a variety of ways, using the tiny pub/sub of Ben Alman, which is a plug-in to jquery.
First, F2 subscribe to "done" signals to the "Signal Center" jquery.
Jquery.subscribe ("Done", F2);
The F1 is then rewritten as follows:
Function F1 () {
settimeout (function () {
F1 's Task code
Jquery.publish ("Done");
}, 1000);
}
Jquery.publish ("done") means that after the execution of the F1, the "Do" signal is released to the "Signal Center" jquery, triggering F2 execution.
In addition, you can unsubscribe (unsubscribe) after F2 completes execution.
Jquery.unsubscribe ("Done", F2);
The nature of this approach is similar to "event monitoring", but it is significantly better than the latter. Because we can monitor the operation of the program by looking at the message center to see how many signals there are and how many subscribers each signal has.
Iv. promises objects
The promises object is a specification proposed by the COMMONJS workgroup to provide a unified interface for asynchronous programming.
Simply put, it's thought that each asynchronous task returns a Promise object that has a then method that allows you to specify a callback function. For example, F1 's callback function, F2, can be written as:
F1 (). then (F2);
The F1 is rewritten as follows (the implementation of jquery is used here):
Function F1 () {
var DFD = $. Deferred ();
settimeout (function () {
F1 's Task code
Dfd.resolve ();
}, 500);
return dfd.promise;
}
The advantage of this is that the callback function has become a chain of writing, the process of the program can be seen very clearly, and a complete set of matching methods, can achieve many powerful functions.
For example, specify multiple callback functions:
F1 (). Then (F2). then (F3);
For example, specify the callback function when an error occurs:
F1 (). Then (F2). Fail (F3);
Moreover, it has a benefit that none of the previous three methods do: If a task is completed, and then a callback function is added, the callback function is executed immediately. So you don't have to worry about missing an event or signal. The disadvantage of this method is that it is relatively difficult to write and understand.
Example
<!doctype html>
<title> Asynchronous Operation example by Masaki </title>
<meta charset= "Utf-8"/>
<meta content= "ie=8" http-equiv= "x-ua-compatible"/>
<meta name= "keywords" Content= "Asynchronous Operation example by Masaki"/>
<meta name= "description" content= "Asynchronous operation example by Masaki"/>
<%= Javascript_incl Ude_tag "Dom.js"%>
<script type= "Text/javascript" charset= "Utf-8" >
Dom.require ("deferred");
Dom.require ("query");
Dom.ready (function () {
var a = dom ("#aaa") [0];
Dom. Deferred.loop (10,function (i) {
a.innerhtml = i+ "<br/>"
});
Dom. Deferred.loop (10,function (i) {
a.innerhtml = String.fromCharCode (i+97) + "<br/>"
});
Dom. Deferred.loop (10,function (i) {
a.innerhtml = "Masaki" +i+ "<br/>"
});
});
/* Results
0
A
Masaki 0
1
Masaki 1
2
C
Masaki 2
3
D
Masaki 3
4
E
Masaki 4
5
F
Masaki 5
6
G
Masaki 6
7
H
Masaki 7
8
I
Masaki 8
9
J
Masaki 9
*/
</script>
<body>
<div id= "AAA" ></div>
</body>
The above approach is based on the concept of JS single-threaded, if interested, you can learn about JavaScript multithreaded programming.