Reputation: 1827
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?
Upvotes: 1
Views: 115
Reputation: 2057
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);
Upvotes: 0
Reputation: 930
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);
}
Upvotes: 1
Reputation: 6561
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);
Upvotes: 0
Reputation: 129792
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.
Upvotes: 3