Re-understanding JavaScript callback functions

Source: Internet
Author: User

Pass the function as a parameter into another function. This function is called a callback function.

It is often the case that A and B layers of a project are performed collaboratively by different people. A layer is responsible for the function FUNA,B layer is responsible for FUNCB. When the B layer is going to use a module's data, he says to the A-level staff, I need you to provide data that satisfies a certain need, and you provide me with an interface.

A-level staff said: I give you data, how to display and deal with the b thing.
Of course, Layer B is not going to provide you with a data interface for each requirement, B provides a pass-through interface to a. B Gets the data, then B writes the function to show.

That is, you need to work with others to provide data, and you don't need to focus on how others get or build the data. You just have to work on the data you've got. This is the time to use the callback function

Therefore, callbacks are essentially a design pattern, and the design principles of jquery (including other frameworks) follow this pattern.

An example of using callbacks in a synchronous (blocking) purpose is to execute FUNC2 after the FUNC1 code execution is complete.

var func1=function(callback) {    //dosomething.    typeof (callback) = = = "function") && callback ();} Func1 (FUNC2);     var func2=function() {}

Examples of asynchronous callbacks:


$ (document). Ready (callback); $.ajax ({ URL: "test.html", context:document.body }). Done (function () { $ (the). AddClass ("Done"); }). Fail (function () { alert ("error"); }). Always (function () { alert (' complete '); });
Note that the AJAX request is indeed asynchronous, but the request is made by the browser to open a new thread request, and when the state of the request changes, if the callback was previously set, the asynchronous thread will produce a state change event to be placed in the processing queue of the JavaScript engine waiting to be processed. See: http://www.phpv.net/html/1700.html

When is the callback executed?

Callback functions, which are typically executed in a synchronous context, may not be executed in an asynchronous context because the event is not triggered or the condition is not satisfied.

Use of callback functions

    • Resource loading: Execute callback after dynamically loading JS file, execute callback after loading IFRAME, Ajax operation Callback, image loading complete execution callback, Ajax and so on.
    • DOM events and node. JS events are based on a callback mechanism (the node. JS callback may have multiple layers of callback nesting issues).
    • SetTimeout delay Time is 0, this hack is often used, settimeout call function is actually a callback embodiment
    • Chained invocation: When chaining calls, it is easy to implement chained calls in the evaluator (setter) method (or in a method that does not have a return value in itself), and the accessor (getter) is relatively bad for chaining calls because you need the accessor to return the data you need instead of the this pointer. If you want to implement a chained method, you can use a callback function to implement
    • The function Call of SetTimeout, SetInterval, gets its return value. Since all two functions are asynchronous, that is, their call timing and the program's main process is relatively independent, so there is no way to wait for their return value in the body, they are opened when the program will not stop waiting, otherwise it will lose the meaning of settimeout and setinterval, So with return there is no point, only using callback. The meaning of callback is to notify the agent function of the result of the timer execution to deal with it in time.

(Refer to: http://segmentfault.com/q/1010000000140970)

Collect the information on the net, should understand, oneself to organize an example:

functionFun (num,callback) {if(num<0) {alert ("Call a-layer function to handle!"); Alert ("Data cannot be negative, input error!"); }Else if(num==0) {alert ("Call a-layer function to handle!"); Alert ("The data item does not exist!" "); }Else{alert ("Call the B-layer function to handle!"); Callback (1); }}functionTest () {varNum=document.getelementbyid ("Score"). Value; Fun (num,function(back) {//Anonymous B-layer processing functions
Alert (":" +back);
if(num<2) Alert ("Number is 1"); Else if(num<=3) Alert (The number is 2 or 3! "); ElseAlert ("The number is greater than 3!"); }) }

When the function starts to execute the fun, run to find out whether NUM is negative or zero, otherwise execute the B-layer processing function alert (":" +back), Output 1, determine <2, <=3, >3 and so on.

Experience Tips:

It is best to ensure that the callback exists and must be a function reference or function expression:
(Callback && typeof (callback) = = = "function") && callback ();

var obj={        function(callback) {        //TODO ...        if typeof (callback) = = = "function") && Callback ()) {              callback (' init ... ');   callback         }    }

Finally, why use a callback function? The following metaphor is very lively and interesting.

You have to go to the next bedroom to find classmates, found that people are not, how do you do?


Method 1, every few minutes to go to the next bedroom, see people in not
Method 2, please, the man with his bedroom, and see him call you when he comes back.

The former is polling and the latter is a callback.

Do you think I can wait for my classmates to come back directly in the next bedroom?

Yes, just so you can save time to do other things, now you have to waste waiting. Turns the original non-blocking asynchronous call into a blocking synchronous call.

JavaScript callbacks are used in asynchronous invocation scenarios and use callbacks to perform better than polling.

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.