Understand javascript callback functions and javascript callback Functions

Source: Internet
Author: User

Understand javascript callback functions and javascript callback Functions

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

In this case, different personnel work together on Layer A and layer B of A project. Layer A is responsible for function funA and layer B is responsible for funcB. When layer B needs to use data of A module, he told layer A that I need you to provide data that meets certain requirements, and you provide me with an interface.

The personnel at Layer A said: I will provide you with data. How to display and process the data is B's business.
Of course, layer B cannot provide A data interface for each of your needs. B provides A data interface for A to obtain data through interface. B, and then B writes the function to display the data.

That is, you need to work with others to provide data, and you do not need to focus on how others obtain or build data. You only need to perform operations on the data obtained. In this case, you need to use the callback function.

Therefore, callback is essentially a design pattern, and the design principles of jQuery (including other frameworks) follow this pattern.

An example of using callback in synchronization (blocking) is to execute func2 after the func1 code is executed.

Copy codeThe Code is as follows:
Var func1 = function (callback ){
// Do something.
(Callback & typeof (callback) === "function") & callback ();
}

Func1 (func2 );
Var func2 = function (){
}

Example of asynchronous callback:

Copy codeThe Code is as follows:
$ (Document). ready (callback );

$. Ajax ({
Url: "test.html ",
Context: document. body
}). Done (function (){
$ (This). addClass ("done ");
}). Fail (function (){
Alert ("error ");
}). Always (function (){
Alert ("complete ");
});

Note that the ajax request is indeed asynchronous, but this request is a new thread request from the browser. When the Request status changes, if the callback has been set previously, this asynchronous thread generates a state change event, which is placed in the processing queue of the JavaScript engine to be processed. See: http://www.phpv.net/html/1700.html

When will the callback be executed?

The callback function is generally last executed in a synchronous situation, but may not be executed in an asynchronous situation because the event is not triggered or the conditions are not met.

Usage of callback Functions

Resource loading: callback is executed after js files are dynamically loaded, callback is executed after iframe is loaded, callback for ajax operations, callback for image loading completion, AJAX, and so on.
DOM events and Node. js events are based on callback mechanisms (Node. js callbacks may cause multi-layer callback nesting issues ).
The latency of setTimeout is 0, which is often used. The settimeout function is actually a callback.

Chained call: When a chained call is made, it is easy to implement chained call in the setter method (or in a method that does not return a value), while getter) it is relatively difficult to implement chained call, because you need the iterator to return the data you need instead of the this pointer. If you want to implement the chained method, you can use the callback function to implement it.

SetTimeout and setInterval functions call to obtain their return values. Because both functions are asynchronous, that is, their call sequence and the main process of the program are relatively independent, there is no way to wait for their return values in the subject, when they are opened, the program will not stop and wait. Otherwise, the meaning of setTimeout and setInterval will be lost. Therefore, it is meaningless to use return, and only callback can be used. Callback notifies the proxy function of the result of timer execution for timely processing.

I should understand the information collected on the Internet. I have prepared an example myself:

Copy codeThe Code is as follows:
Function fun (num, callback ){
If (num <0 ){
Alert ("Call layer A function for processing! ");
Alert ("data cannot be negative. input error! ");
} Else if (num = 0 ){
Alert ("Call layer A function for processing! ");
Alert ("this data item does not exist! ");
} Else {
Alert ("call B-layer function processing! ");
Callback (1 );
}
}
Function test (){
Var num = document. getElementById ("score"). value;
Fun (num, function (back) {// anonymous B-layer processing function
Alert (":" + back );
If (num <2)
Alert ("number: 1 ");
Else if (num <= 3)
Alert ("number is 2 or 3! ");
Else
Alert ("the number is greater than 3! ");
})
}

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

TIPS:

It is best to ensure that the callback exists and must be a function reference or function expression:

Copy codeThe Code is as follows:
(Callback & typeof (callback) === "function") & callback ();

Copy codeThe Code is as follows:
Var obj = {
Init: function (callback ){
// TODO...
If (callback & typeof (callback) = "function") & callback ()){
Callback ('init... '); // callback
}
}

 
Finally, why should I use the callback function? The following metaphor is lively and interesting.

What do you do if you go to the dormitory next door and find someone else is absent?

Method 1: Go to the next bedroom every few minutes.
Method 2. Please contact the person in the same dormitory and call you when he returns.

The former is polling, and the latter is callback.

Then you said, can I wait for my classmates to return directly in the dormitory next door?

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

JavaScript callback is used in asynchronous call scenarios. The callback performance is better than that of 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.