Understanding JavaScript Callback Functions _ Basics

Source: Internet
Author: User
Tags setinterval

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

It is often the case that the layer A and B of a project are coordinated by different people. Layer A is responsible for the function funa,b layer FUNCB. When layer B uses data from a module, he says to level A, "I need you to provide data that meets a certain requirement, and you provide me with an interface."

A level of people said: "I give you data, how to show and deal with is a B thing."
Of course, Layer B is not going to provide you with a data interface for each requirement, B provides a passing interface for a. B Gets the data, then B writes the function to show it.

That is, you need to work with other people to provide the data, and you don't need to focus on how people get or build the data. All you have to do is manipulate the data that you get. Then you need to use the callback function

As a result, 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 synchronization (blocking) to execute FUNC2 after func1 code execution completes.

Copy Code code as follows:

var func1=function (callback) {
Do something.
(Callback && typeof (callback) = = "function") && callback ();
}

Func1 (FUNC2);
var func2=function () {
}

Example of an asynchronous callback:

Copy Code code 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, and when the requested state changes, if the callback was previously set, the asynchronous thread is placed in the processing queue of the JavaScript engine waiting to be processed. See: http://www.phpv.net/html/1700.html

When will the callback be executed?

Callback functions, which are generally executed in the context of synchronization, 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: Dynamically loading JS files after the callback, loading the IFRAME to perform the callback, Ajax operation callback, picture loading complete execution callback, Ajax and so on.
DOM events and Node.js events are based on a callback mechanism (a Node.js callback may have problems with multi-tier callback nesting).
SetTimeout delay Time is 0, this hack is often used, settimeout called function is actually a callback embodiment

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

The settimeout, setinterval function call gets its return value. Since two functions are asynchronous, that is: their call time sequence and the main process of the program is relatively independent, so there is no way to wait for their return value in the main body, they are opened when the program will not stop to wait, otherwise it will lose the meaning of settimeout and setinterval, So using return has no meaning, only use callback. The significance of the callback is to notify the agent function of the result of the timer execution to be processed in time.

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

Copy Code code as follows:

function Fun (num,callback) {
if (num<0) {
Alert ("Call a layer function processing!");
Alert ("Data cannot be negative, input error!");
}else if (num==0) {
Alert ("Call a layer function 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 (back) {//anonymous B-layer processing function (num,function)
Alert (":" +back);
if (num<2)
Alert ("Number 1");
else if (num<=3)
Alert ("Number is 2 or 3!") ");
Else
Alert ("Number greater than 3!");
})
}

When the function begins to execute fun, first run to find out whether NUM is a negative or zero, otherwise perform the B-level processing function alert (":" +back), output 1, the decision is <2, <=3, >3 and so on.

Experience Tips:

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

Copy Code code as follows:

(Callback && typeof (callback) = = "function") && callback ();

Copy Code code as follows:

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


Finally, why do you want to 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 again to visit the next bedroom, to see people in not
Method 2, please be with his roommate and see him call you when he gets back.

The former is polling, and the latter is callback.

Then you say, I directly in the next bedroom to wait for the classmate to come back?

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

JavaScript callbacks are used in asynchronous invocation scenarios and use callback performance 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.