Lesson 29th: JavaScript Asynchronous processing

Source: Internet
Author: User
Tags try catch

Do you know how many methods in JavaScript are available for asynchronous processing? SetTimeout (), SetInterval () is the most commonly used two. The XMLHttpRequest object, when the AJAX request is made. PostMessage () When cross-domain operations are performed. Webworker when a new thread is created. The Setimmediate method (the new SetTimeout method). Requestanimationframe the animation operation. All of these things have a common feature, which is to have a callback function. Some asynchronous APIs also provide a corresponding interrupt API, such as: Cleartimeout,clearinterval,clearimmediate,cancelanimationframe.

Early in the year, we are through the settimeout and setinterval on the Web page animation, this animation is actually through the asynchronous API calls the same callback method, the callback method in the face of some elements of the element node in a small range of changes.

First of all, let's talk about the two APIs of SetTimeout and SetInterval, and here are just a few of the most common points of knowledge:

(1) Their callback method, if the execution time is greater than the interval time (for example: setinterval () (function () {The event that executes the code is greater than 50 milliseconds},50)), then the actual interval time will be greater than 50 milliseconds (because the JS execution thread is actually a queue, It executes a function before executing another function, so this code means: every 50 milliseconds, to add a function to the execution thread, if the execution thread executes this function, and then a function, after which the function will be queued, waiting for the previous function to complete, it will be executed, Therefore, the function execution interval is actually greater than 50 milliseconds.

(2) They have a minimum clock interval of ie6-8 under 15.6MS,IE9 for 10MS,IE10 and other standard browsers of 4ms. This means that if you setinterval (Functiojn () {},1), this code means to perform the function once in a millisecond, but in fact, the browser has a minimum interval, even if you write 1ms, It also performs the function according to its minimum event interval (for example, IE6-8 will perform a function only 15.6 milliseconds). If you feel ie6-8, the shortest clock interval is too large, you can use the image dead chain to perform the onerror callback immediately when the situation is modified, such as:

var orig_settimeout = window.settimeout;

Window.settimeout = function (callback,time) {

if (Time > 15) {

Orig_settimeout (Callback,time);

}

else{ //When the interval is less than 15 milliseconds, a new image object is created, giving it an incorrect SRC, which immediately calls the OnError callback method, and executes the callback, which enables a function that is less than 15 milliseconds apart.

var img = new Image ();

Img.onload = Img.onerror = function () {

Callback ();

};

IMG.SRC = "Data:,foo";

}

}

(3) Do not write the second parameter, the browser automatically allocate time, Ie,firefox, the first allocation may give a 100ms, will slowly shrink to the minimum clock interval. The Safari,chrome,opera is assigned a 10ms. In Firefox, SetInterval does not write a second parameter, it is treated as settimeout, and is executed only once.

(4) ie10+ and standard browsers support additional parameters, starting with the third parameter and passing in as a callback parameter. For example: SetTimeout (function () {},1000,1,2,4), then [].slice.call (arguments) = [1,2,4] in function. Ie6-9 can simulate this:

if (ie9-) {

(function (Overridefun) {

Window.settimeout = Overridefun (window.settimeout);

Window.setinterval = Overridefun (window.setinterval);

})

(

function (Originalfun) {

return function (callback, delay) {

var args = [].slice.call (arguments,2); //Start with the third parameter

Return Originalfun (function () {

if (typeof callback = = "string") { //If the first parameter passed in a string

Eval (callback);

}else{

Callback.apply (This,args); //Pass parameters to the callback method

}

},delay);

};

}

)

}

(5) If the event parameter of the SetTimeout method is negative or 0 or a large positive number, the standard browser is executed immediately, and the old version of IE processing will have a large difference without study.

Next, let's explain the predecessor of the Deferred object (Ajax asynchronous processing object in jquery), MochiKit Deferred.

Deferred is now the most famous asynchronous model, it was originally a Python twisted framework of a class, and was later introduced by the MochiKit framework, the latter was copied by dojo, after the introduction of jquery. Let's take a detailed look at the implementation principle of the MochiKit Deferred (the next Deferred refers to MochiKit Deferred):

Deferred internal callback is divided into two, one is a successful callback for normal execution, a call error callback, used for error execution. Each consists of two queues, which we can call the success queue and the error queue. When a callback is added, it is added to a set of (successful callbacks and error callbacks), each set of callbacks executes only one (not a successful callback, or an error callback), each set of callbacks received is the result of the previous set of callback processing, only the first set of callbacks received by the user passed the parameter. So how to decide whether to execute a successful callback or error callback, but also based on the results of the previous group, if the result of the previous group throws an error, then this group will execute an error callback, if this group of error callback does not throw an error, then the next set of callbacks will execute a successful callback. The first set of execution is user-determined, meaning that the user invokes a successful callback method, the execution of a successful callback, the user executes the error callback method to execute the error callback.

Let's take a look at the method inside the deferred:

Addcallback the method to add a successful callback.

Adderrback How to add error callbacks

Addboth simultaneous addition of normal callback and error callback method

The Addcallbacks method is called inside all three methods, and the parameter of this method can only be two functions or a function of one null. This means that the above three methods convert the arguments to two functions or a function of NULL, and then pass them to the Addcallbacks method. The deferred instance has a chain array property, and each item in the array is an array of two elements, such as:

Deferred.chain = [[Callback,errorcallback], [Callback1,errorcallback1], [Callback2,errorcallback2]];

As an example:

var d = new Deferred ();

D.addcallback (Mycallback);

D.adderrback (Myerrback);

D.addboth (Myboth);

D.addcallbacks (Mycallback,myerrback);

At this point, D.chain = [[Mycallback, NULL], [NULL, Myerrback], [Myboth, Myboth], [Mycallback, Myerrback]];

Triggering these callbacks is done by invoking the D.callback and D.errback methods. The process inside the two methods is consistent, first check that the deferred object has not been called, and if not, call the _resback method.

Of course, the user can pass in callback or Errback parameters, the parameters passed in the _resback method will generate an array, if the call is the callback method (successful callback), then put the parameters in the first position of the array, If the Errback method is called (a failed callback), then the parameter is placed in the second position of the array. The _resback method then determines whether the execution has been severed (the asynchronous process has not been terminated), and if not, calls the _fire method to execute the callback.

The _fire method is to continually eject a set of functions in the chain array, take the first callback from the state or the second callback (the first is a successful callback, the second is a failed callback), and each group of callbacks receives the return value of the previous set of callbacks as a parameter. As an example:

function increment (value) {

Console.log (value);

return value+1;

}

var d = new Deferred ();

D.addcallback (increment); //d.chain = [[Increment,null]]

D.addcallback (increment); //d.chain = [[Increment,null],[increment,null]]

D.addcallback (increment); //d.chain = [[Increment,null],[increment,null],[increment,null]]

D.callback (1); //_resback (1), [1,null], Fire ([1,null]), loops out each set of functions in D.chain, because the first entry of the incoming array is 1, which represents a successful callback, Therefore executes the first set of functions of the successful callback increment method, then print out 1, return 2, and this 2 will continue to pass to the second set of functions, because it is also a successful callback, so the second set of functions to execute the successful callback increment method, print 2, return 3. And so on

Then when does the failure callback execute, in the above execution process, there will be a try catch, if the callback method throws an error, it will catch, and then execute the next set of functions in the failure callback. As an example:

var d = new Deferred ();

D.addcallback (function (a) {Console.log (a); return 4}). Addboth (function (a) {Console.log (a); throw "Throw Wrong"},function (b) { Console.log (b); return "XX"}). Addboth (function (a) {Console.log (a); return "normal"},function (b) {console.log (b); return " Error "}"). Addboth (function (a) {Console.log (A + "normal")},function (b) {Console.log (+ + "continued error")})

D.callback (3);

Because the call is the callback method is a successful callback, so print out a (that is, 3), return 4 to the next set of functions, the next set of functions receive this 4, because there is no throw error, so is a successful callback, so print out 4,throw "Throw the wrong", then the next set of functions, the failure callback will be executed, That is, function (b) {console.log (b); return "Error"}, print error: Wrong, return "error", there is no throw error, but normal return "error" the string, so the next set of functions, will execute a successful callback, That is, function (a) {Console.log (A + "normal")}, printing out "normal error".

In MochiKit, deferred also has an important function that can be returned to multiple AJAX request results, and then do the processing. It is implemented using Deferredlist. Early jquery and prototype did not have this thing, they were previously implemented using counters, very complex. As an example:

There is a business that needs to initiate 4 AJAX requests, the addresses of the 4 requests are not the same as the return time, and must wait until they are all processed, consolidate their 4 return data, then initiate two AJAX requests based on the consolidated data, and wait until all two AJAX requests are processed. Once the data for both requests is consolidated, an AJAX request is made, and the return data is counted as a business processing success. If you don't use asynchronous objects for processing, you can think about how complex your code will be, and how easy it is to make mistakes. If you use Deferredlist to implement, it is very simple to put the 4 Ajax requests into the Defrredlist object D1, and then all 4 AJAX processing completed, will trigger the Defrredlist object callback, and in this callback to the 4 requested data consolidation And then initiate two AJAX requests based on the consolidated data, and the two AJAX requests are placed in a Defrredlist object D2, and when all two AJAX requests are processed, the D2 callback method is executed, and finally the 2 requested data is consolidated in this callback. Send the last Ajax request and it's OK.

In the next lesson, we will explain the Jsdeferred object, which basically lays the paradigm that is later called promise/a.

Come on!

Lesson 29th: JavaScript Asynchronous processing

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.