Talk about javascript callback functions

  • 2020-03-30 04:31:31
  • OfStack

Pass the function as an argument to another function. This function is what we call alpha The callback function

It is often encountered that the A and B layers of A project are completed jointly by different people. The A layer is responsible for function funA, while the B layer is responsible for funcB. When layer B is going to use the data of A module, he says to layer A, I need you to provide the data that meets A certain requirement, you provide me with an interface.

The person at level A said, "I will provide you with the data, and how to present and deal with it is the matter of B."
Of course, layer B cannot provide you with A data interface for every requirement, while layer B provides an interface for A to pass through.

That is, you need to collaborate with other people, who provide the data, and you don't need to focus on how other people get or build the data. You just manipulate the data that you get. This is where the callback function comes in

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

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

Examples of asynchronous callbacks:

$(document).ready(callback);     $.ajax({
        url: "test.html",
        context: document.body
    }).done(function() {
    }).fail(function() {
    }).always(function() {

Note that the ajax request is indeed asynchronous, but it is a new thread request made by the browser, and when the state of the request changes, if a callback was previously set, the asynchronous thread generates a state change event and puts it on the JavaScript engine's processing queue for processing. See: (link:

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 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.

Collect data on the net, should understand, oneself sort out an example:

function fun(num,callback){
    if(num<0)  {
        alert(" call A Layer function processing !");
        alert(" The data cannot be negative , Input error !");
    }else if(num==0){
        alert(" call A Layer function processing !");
        alert(" This data item does not exist! ");
        alert(" call B Layer function processing !");
function test(){
    var num=document.getElementById("score").value;
    fun(num,function(back){ //Anonymous B layer handler
            alert(" Numbers for 1");
        else if(num<=3)
            alert(" Numbers for 2 or 3 ! ");
            alert(" Numbers greater than 3!");

When the function starts executing fun, run to determine whether num is negative or zero, otherwise execute the B layer alert(":"+back); Output 1, determined as < 2, < = 3, > 3. Etc.

Tips for experience:

It is best to ensure that the callback exists and must be a function reference or function expression:
(callback && typeof(callback) === "function");

 var obj={
        init : function(callback){
        //TODO ...
        if(callback && typeof(callback) === "function") && callback()){
              callback('init...');//The callback < br / >         }

Finally, why use callback functions? The following metaphor is very vivid and interesting.

You have something to go to the next bedroom to look for a classmate, find the person is not in, how do you do?

Method 1, every few minutes to go to the next bedroom, see people in not
Method 2, ask his roommate to call you when he comes back

The former is a poll and the latter a callback.

Then you say, I directly in the next bedroom until the students come back can?

Yes, but instead of saving time for other things, you have to waste it waiting. The original non - blocking asynchronous call into a blocking synchronous call.

JavaScript callbacks are used in asynchronous invocation scenarios and perform better with callbacks than polling.

A little easier:

"I'm leaving now. I'll let you know when I get there."
This is an asynchronous process, where "I'm off" (the function executes), "you" can do anything, "here" (the function completes), "notify you" (the callback) goes on

Related articles: