Working notes for JavaScript asynchronous programming

Source: Internet
Author: User
Tags bind

JavaScript's execution engine is single-threaded, and is normally the mode of synchronous programming, where the program executes sequentially from top to bottom in order of code. As long as one task takes a long time, the subsequent tasks must be queued up, delaying the execution of the entire program. Common browsers do not respond (suspended animation), often because a section of JavaScript code for a long time (such as a dead loop), then any UI updates will be blocked during execution, interface event processing will also stop responding. Causes the entire page to be stuck in this place and other tasks cannot be performed.

Especially in the FOR Loop statement, if the for loop's processing logic is more complex, and the loop is too many times, more than 1000 times, the execution of JavaScript will block the browser to deal with the obvious suspended animation state. The reason is that the browser when invoking JavaScript, the main interface is to stop responding, because the CPU to the implementation of JS, there is no time to deal with interface messages.

To solve the problem of card death, many people put forward the solution of asynchronous programming, which is one of the ways of performance optimization, in the browser, time-consuming operations should be executed asynchronously, to avoid the browser loss of response. Now the fire Nodejs is asynchronous programming, such as routing, IO Operations, all asynchronous.

In the front-end page implementation, the most common asynchronous is AJAX operations, request an AJAX without waiting for Ajax to return, you can continue the operation of the page.

Others are implemented asynchronously via Settimeout,setinterval,image.onload, Postmessage,webwork, and so on.

There are also many libraries on the Internet to implement asynchronous programming such as: Do.js Step.js, Async.js, flow.js, do not elaborate, interested in Google to understand.

This is mainly about how settimeout implements asynchronous programming.

The code is as follows Copy Code

<! DOCTYPE html>
<title>demo</title>
< Script src= "/jquery-1.10.2.min.js" ></script>
<script>
var updatesync =  function () {
for (var i = 0; I < 10000 i++) {
$ (' #js_output '). text (i);
}
}
 
var updateasync = function () {
var i = 0;
 
Function Updatelater () {
$ (' #js_out Put '). Text (i++);
if (I < 10000) {
settimeout (updatelater, 0);
}
}
Updatelater ();
}
</script>
<body>
<button onclick= "Updatesync ()" > Sync demo</button>
<button Onclick= "Updateasync ()" > Asynchronous Demo</button>
 
<div id= "Js_output" ></DIV>
</ Body>

Click Sync Demo: You will feel the button press down when the card, and then see a final result of 99999, without the intermediate process, this is because the Updatesync function is running in the process of the UI update is blocked, only if it ends after the UI update.

Click Asynchronous Demo: You will see the UI interface from 0 to 999 to update the process quickly, this is the result of asynchronous execution.
The function first declares a local variable i and nested function updatelater, and then calls Updatelater, in which the content of the output node is updated first and then the Updatelater function is executed asynchronously via settimeout. This is actually a recursive call. Any for loops can be transformed into the form of recursive calls.

Why use SetTimeout (fn,0), still can see the quick update? This is because although his delay is set to 0, almost instantaneously, it is added to the execution queue, but this is the process where the render is done and the output is already the updated value when the callback function executes.

The result is clearly that the asynchronous operation does not block the UI and you can continue to perform other browser operations. Let the UI operate more smoothly, but there are also disadvantages to asynchronous programming, such as the code above, which uses settimeout asynchronous methods, which are more time-consuming than synchronous execution in terms of overall code execution efficiency. At the same time because it is asynchronous execution, interrupts the original code execution sequence, resulting in nested function calls, destroying the original simple logic, so that the code difficult to read.

It is easy to implement in synchronous programming when judging whether the execution is complete, and the code is written behind the For loop. and asynchronous words, you need to make some judgments.

Or the example above, how do I perform a callback after the loop is over? Can use jquery's $.when, and $. Deferred method, of course, you can write the callback function, but it does not look so elegant.

The code is as follows Copy Code

var wait = function () {
var DTD = $. Deferred ();

var i = 0;

function Updatelater () {
$ (' #js_output '). Text (i++);
if (I < 1000) {
settimeout (updatelater, 0);
}
if (i = = 1000) {
Dtd.resolve (); Change the execution state of a deferred object
}
}
Updatelater ();

return Dtd.promise (); Returns the Promise Object
}

var updateasyncback = function () {
$.when (Wait ()). Done (function () {
Alert (' done! ');
})
}

Add:

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 comparatively difficult to write and understand.

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.