JavaScript's callback function (callback)

Source: Internet
Author: User

1. callback function Definition: 

A callback function is a function that is called through a function pointer. If you pass the pointer (address) of the function as an argument to another function, when the pointer is used to invoke the function it points to, we say this is a callback function. The callback function is not called directly by the implementing party of the function, but is invoked by another party when a particular event or condition occurs, and is used to respond to the event or condition.

In JavaScript, the callback function is specifically defined as: function A is passed as a parameter (function reference) to another function B, and this function B executes function A. Let's just say that function A is called a callback function. If there is no Name (function expression), it is called an anonymous callback function. So callback is not necessarily used for asynchrony, and callbacks are often used in scenarios where general synchronization (blocking) is required, such as executing a callback function after certain operations have been performed.

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.

Example: an example of a synchronous (blocking) callback used to execute FUNC2 after the FUNC1 code execution is complete.

var func1=function (callback) {

Do something

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

}

Example: an example of an asynchronous callback

$ (document). Ready (callback);

$.ajax ({

  URL: "Test.html";

  Context:document.body

}). Done (function () {

  $ (this). AddClass ("Done");

}). Fail (function () {

  Alert ("Error");

}). Always (function () {

  Alert ("complete");

})

In JavaScript, functions are also objects and functions are function objects created with the Functon () constructor. The function object contains a string that contains the JavaScript code for the functions. This allows you to pass functions as arguments to other functions.

Example of a function being passed as a parameter:

function fn (arg1,arg2,callback) {

var Num=math.ceil (Math.random () * (ARG1-ARG2) +arg2);

Callback (NUM);

}

FN (10,20,function (num) {

Console.log ("Callback called! Num: "+num);

}) 

The traditional function enters data as a parameter and returns a value using the return statement. Theoretically, there is a return statement at the end of the function that is structured as an input point and an output point. It is easier to understand that a function is essentially a mapping of the implementation process between input and output.

However, when the implementation of the function is very long, do you choose to wait for the function to finish processing, or use the callback function for asynchronous processing? In this case, it becomes critical to use a callback function, such as an AJAX request. If the callback function is used for processing, the code can proceed with other tasks without having to wait. In practice, asynchronous calls are often used in JavaScript, and even here it is highly recommended!

2, the use of callback function occasions

(1) Resource loading: Execute callback after dynamically loading JS file, execute callback after loading IFRAME, Ajax operation Callback, image loading complete execution callback, etc.

(2) Dom events and node. JS events based on callback mechanism

(3) The SetTimeout delay time is a function of the 0,settimeout call is actually a callback embodiment

(4) Chained invocation: When chaining calls, it is easy to implement chained calls in the evaluator (setter) method, while 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 SetTimeout, setinterval function calls to get their 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.

3. Transfer of callback function

$.get (' myhtmlpage.html ', mycallback); This is right.

$.get (' myhtmlpage.html ', Mycallback (' foo ', ' Bar ')); This is wrong, to take the parameters implemented as follows

$.get (' myhtmlpage.html ', function () {

function expressions with parameters

Mycallback (' foo ', ' Bar ');

});

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

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

Reference Original: Http://www.jb51.net/article/54750.htm

 

JavaScript's callback function (callback)

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.