JavaScript callback function

Source: Internet
Author: User
Tags setinterval


One, the callback function defines

Baidu Encyclopedia: callback function

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.

Example

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) {    //do something.    (Callback && typeof (callback) = = = "function") && callback ();} Func1 (FUNC2);    var func2=function () {}

  

Two, the use of callback function occasions
    • 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.

functions are also objects

To figure out the callback function, you first have a clear understanding of the rules of the function. In JavaScript, the function is rather strange, but it is indeed an object. To be precise, a function object is created with a function () constructor. The function object contains a string that contains the JavaScript code for the functions. If you're transferring from C or Java, it might seem odd how the code might be a string. But for JavaScript, this is common. The difference between the data and the code is very vague.

//可以这样创建函数var fn = new Function("arg1", "arg2", "return arg1 * arg2;");fn(2, 3);   //6

One benefit of this is that you can pass code to other functions, or you can pass a regular variable or object (because the code is literally just an object).

Transfer function as callback

It is easy to pass a function as a parameter.

function fn (arg1, arg2, callback) {    var num = Math.ceil (Math.random () * (ARG1-ARG2) + arg2);    Callback (num);//pass result}FN (num) {   console.log ("Callback called! NUM: "+ num";}); /result is a random number between 10 and 20

  

It might seem like a bit of a hassle, maybe even a little silly, why not return the results normally? But when it comes to the need to use a callback function, you may not think so!

Get out of the way

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!

The following is a more comprehensive example of using AJAX to load an XML file, and using the call () function to invoke a callback function in the context of the request object (requested objects).

function fn (URL, callback) {    var HttpRequest; Create xhr    HttpRequest = window. XMLHttpRequest? New XMLHttpRequest ():    window. ActiveXObject? New ActiveXObject ("Microsoft.XMLHTTP"             ): undefined;//functional detection for IE    httprequest.onreadystatechange = function () {      if (httprequest.readystate = = = 4                 && Httprequest.status = = = 200) {//Status judgment          Callback.call ( httprequest.responsexml);         }    };    Httprequest.open ("GET", url);    Httprequest.send ();}   FN ("Text.xml", function () {//Call functions   console.log (this);  After this statement output}); Console.log ("This would run before the above callback."); This statement first outputs

  

We request asynchronous processing, which means that when we start the request, we tell them to call our function when it's done. In fact, the onReadyStateChange event handler also takes into account the failure of the request, where we assume that the XML file exists and can be successfully loaded by the browser. In this example, the Async function is assigned to the onReadyStateChange event, so it is not executed immediately.

Finally, the second Console.log statement executes first, because the callback function executes until the request is complete.

The above example is not easy to understand, so take a look at the following example:

function foo () {    var a = ten;    return function () {        a *= 2;        return A;           };   } var f = foo (); F (); return 20.f (); Return 40.

  

function is called externally, the variable a can still be accessed. This is because the scopes in JavaScript are lexical in nature. Functions run in the scope in which they are defined (within the scope of Foo inside the example above), not in the scope in which this function is run. As long as f is defined in Foo, it can access all the variables defined in Foo, even if the execution of Foo is finished. Because its scope is preserved, only the function that is returned can access the saved scope. Returning an inline anonymous function is the most common means of creating closures.

Third, reference
  1. Understanding JavaScript Callback Functions
  2. Understand and use the callback function in JavaScript (this is pretty good)
  3. JavaScript callback function

JavaScript callback function (GO)

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.