javascript - What is the difference between a callback function and a normal calling function?
欧阳克
欧阳克 2017-06-26 10:53:07
0
2
1402

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?

欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

reply all(2)
淡淡烟草味

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.

漂亮男人

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template