search

Home  >  Q&A  >  body text

javascript - What is the difference between a callback function and a normal calling function?

The definition of the callback function is to pass the b function as a parameter to a for execution. At this time, b is the callback function. I suddenly have a question, what is the difference between it and directly calling b in the a function?
I wrote a demo myself

function a(){
    b();
    console.log('hello world');
}
function b(){
    var n = 0;
    for(var i = 0;i < 1000000000;i++){
        n++;
    }
    return n;
}
a(); //hello world

It takes about 3 seconds to see the output result, and then rewrite it in the form of a callback function

function a(callback){
    callback.call(this);
    console.log('hello world');
}
function b(){
    var n = 0;
    for(var i = 0;i < 1000000000;i++){
    }
    console.log(1);
}
a(b); //hello world

The output result can only be seen after 3 seconds.
I have found many articles, all of which explain that when b is executed as the callback function of function a, it does not hinder the normal execution of function a. According to this logic, the second The method should be to output hello world immediately. Did I use the wrong callback function? Still have trouble understanding?

欧阳克欧阳克2741 days ago1428

reply all(2)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-06-26 10:55:07

    1. There is no difference in performance
    2. The callback function is passed as a parameter, and the operation is more flexible. For example, you can define a function c, which can be run
    b(c), when you run the function within the function, Variable flexibility is lost.

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-26 10:55:07

    Well, you misunderstood, the effect of calling is the same. There is also callback.call(this); which is superfluous and is the same as callback()’s this.

    The advantage of callbacks is dependency inversion. You can let a call c, d, e without modifying the code of a...

    reply
    0
  • Cancelreply