简体   繁体   中英

callback function vs calling a function from inside the function

I'm trying to understand JS and I'm really confused by the callback pattern.

function one(){
    alert("I'm one!")
}

function total(arg, callback){
    setTimeout(function() {alert("I'm "+arg);}, 1000);
    callback();
}

total('all', one);

versus

function one(){
    alert("I'm one!")
}

function total(arg){
    setTimeout(function() {alert("I'm "+arg);}, 1000);
    one();
}

total('all');

What is the benefit of passing one() as a parameter vs just calling it from within the function?

If you know that you're always going to call one , there's no need to accept it as an input parameter; you can just go ahead and call it.

The ability to accept callbacks allows you to easily write loosely coupled code.

You are, for instance, passing a callback to setTimeout in your code example. setTimeout knows to wait a given number of milliseconds before a function is called, but it doesn't know which function to call.

Passing in callback functions allows you to dynamically affect the flow of the program. Additionally, you could pass the outcome of total as a parameter to callback , which is often used to enable asynchronous programming.

function one(){
  alert("I'm one!")
}

function total(arg, callback){
  setTimeout(function() {
    if (callback) {
      callback();
    }
  }, 1000);
}

I suspect that your examples are not what was intended to showcase what a callback is. Does this make more sense?

function cb(arg){
    alert("I'm "+arg+"!")
}

function total(arg, callback){
    setTimeout(callback, 1000, arg);
}

total('one', cb);

Callback argument allows you to define custom interaction. It's commonly used with any asynchronous operation to allow reacting of state change (for example when operation is done, or errored).

One example of that may be an AJAX call (here with jQuery for simpliciy):

var request = $.ajax({
    url: "script.php"
});

// this allows you to specify custom action handling
request.done(one);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM