Tell you what a javascript callback function is

  • 2020-03-30 03:51:51
  • OfStack

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 functions like 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);  //Deliver results

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
 httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() :   //Functional detection for IE
    window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : undefined;
 httpRequest.onreadystatechange = function(){
  if(httpRequest.readystate === 4 && httpRequest.status === 200){  //State judgment; 
 };"GET", url);

fn("text.xml", function(){    //Call a function
 console.log(this);   //Output after this statement

console.log("this will run before the above callback.");  //This statement is printed first

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.

What is a callback?

See the wiki Callback_(computer_programming) entry:

In computer programming, a callback is a reference to a piece of executable code that is passed as an argument to other code.

How jQuery Works#Callback_and_Functio... Items:

A callback is A function that is passed as an argument to another function and is executed after its parent function has completed. The special thing about A callback is that functions that appear After the "parent" can execute before the callback executes. Another important thing to know is how to forget the callback. This is where I have often forgotten the proper syntax.

Encyclopedia: callback function

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.

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

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.

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();

  var func2=function(){

Examples of asynchronous callbacks:


 url: "test.html",
 context: document.body
}).done(function() { 
}).fail(function() { alert("error");
}).always(function() { alert("complete"); 

When is the callback executed

Callbacks, which are usually executed last in the synchronous case, may not be executed in the asynchronous case because the event is not triggered or the condition is not satisfied.

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 use the callback function to realize the setTimeout and setInterval function calls to get 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.

Passing of the callback function

As mentioned above, you pass a function reference or a function expression as an argument.

$.get('myhtmlpage.html', myCallBack);//That's right
$.get('myhtmlpage.html', myCallBack('foo', 'bar'));//That's wrong. What about taking parameters?
$.get('myhtmlpage.html', function(){//Use function expressions with arguments
myCallBack('foo', 'bar');

In addition, it is best to ensure that the callback exists and must be a function reference or function expression:
(callback & amp; & amp; Typeof (the callback) = = = "function") & amp; & amp; The callback ();

Related articles: