Javascript callback function details

  • 2020-03-30 04:16:29
  • OfStack

Callback function definition

A callback function is a function called through a function pointer. If you pass a function's pointer (address) as an argument to another function, we say it is a callback function when the pointer is used to call the function it points to. The callback function is not called directly by the implementers of the function, but by the other party when a particular event or condition occurs, in response to that event or condition.

In JavaScript, A callback function is defined as passing function A as an argument (function reference) to another function B, and this function B executes function A. Let's say that function A is called A callback function. If there is no name (function expression), it is called an anonymous callback function. Therefore, a callback is not necessarily used for asynchrony, and is often used in synchronous (blocking) scenarios, such as requiring a callback function to be executed after some operation.

example
An example of using a callback in synchronization (blocking) to execute func2 after the func1 code execution completes.


var func1=function(callback){
    //do something.
    (callback && typeof(callback) === "function") && callback();
}
func1(func2);
    var func2=function(){
}

Where to use the callback function
Resource loading: callback after dynamic loading of js file, callback after loading of iframe, ajax operation callback, image loading callback, ajax, etc.

DOM events and node.js events are based on a callback mechanism (node.js callbacks can cause problems with multiple layers of nested callbacks).
The delay time of setTimeout is 0. This hack is often used, and the function called by setTimeout is actually a callback

Chain call: chain call, in the assignment editor (setter) method (or itself has no return value method) is easy to implement chain calls, and device (getter) values are relatively bad implementation chain calls, because you need value is return a pointer to the data you need rather than this, if you want to achieve chain method, can be done using the callback function

The function call of setTimeout, setInterval gets its return value. Because of the two functions are asynchronous, i.e., they call the main process of timing and the procedure is relatively independent, so the body inside have no way to wait until they return values, when they are open program will not stop to wait for, otherwise will lose the meaning of the setTimeout and setInterval, so there was no point in return, can only use the callback. The point of callback is to notify the broker function of the result of a timer execution for timely processing.

Functions are also objects

To understand the callback function, you must first clearly understand the function's rules. In javascript, functions are weird, but they are objects. Rather, a Function is a Function object created with the Function() constructor. The Function object contains a string that contains the javascript code for the Function. If you're coming from the C language or the Java language, which might seem strange, how can the code be a string? But with javascript, this is pretty common. The distinction between data and code is fuzzy.


//You can create the function
by doing this var fn = new Function("arg1", "arg2", "return arg1 * arg2;");
fn(2, 3);   //6

One advantage of this is that you can pass code to other functions, as well as regular variables or objects (because the code is literally just an object).

Pass the function as a callback

It's easy to pass a function as an argument.


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

This might seem like a bit of a hassle, or even a bit of a silly thing to do, why not return the results normally? But when you have to use a callback function, you might not think so!

Get out of the way!

Traditional functions enter data as arguments and return values using return statements. In theory, at the end of the function there is a return return statement, the structure is: an input point and an output point. This is easy to understand; functions are essentially mappings between the input and the output.

However, when the function implementation process is very long, do you choose to wait for the function to complete processing, or use the callback function for asynchronous processing? In this case, using callback functions, such as an AJAX request, becomes critical. If the callback function is used for processing, the code can proceed to other tasks without waiting. In practice, asynchronous invocation is often used in javascript, and is even highly recommended here!

Here's a more comprehensive example of loading an XML file using AJAX, and using the call() function, which calls the callback function in the context of the requested object.


function fn(url, callback){
    var httpRequest;    //Create XHR < br / >     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 determination
          callback.call(httpRequest.responseXML); 
       }
    };
    httpRequest.open("GET", url);
    httpRequest.send();
} fn("text.xml", function(){    //Call the function
   console.log(this);   //Output
after this statement }); console.log("this will 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 finished. In practice, the onreadystatechange event handler would also have to consider the case where the request fails, assuming that the XML file exists and can be successfully loaded by the browser. In this case, the asynchronous function is assigned to the onreadystatechange event, so it is not executed immediately.

Finally, the second console.log statement is executed first, because the callback function does not execute until the request completes.

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


function foo(){
    var a = 10;
    return function(){
        a *= 2;
        return a;      
    };  
}
var f = foo();
f(); //return 20.
f(); //return 40.

The function is called externally, and you can still access the variable a. This is all because scopes in javascript are lexical. Functions run in the scope where they are defined (the scope inside foo in the example above), not in the scope where the function is run. As long as f is defined in foo, it has access to all the variables defined in foo, even if execution of foo has ended. Because its scope is saved, but only the returned function can access the saved scope. Returning an embedded anonymous function is the most common way to create a closure.


Related articles: