0

I am trying to understand the callback functionality in Javascript. Please find the below code that I have written.

var genericFunction=function(arg1, arg2, callback){
  var result=setTimeout(callback(arg1, arg2), 1000);
  console.log('Result >> '+result)
  return result;
}

var sum=function(arg1, arg2){
  return arg1+arg2;
}

console.log(genericFunction(2,5,sum));
console.log('After calling the genericFUnction call.');

I am assuming that the the message After calling the genericFunction call. should be printed and then later after 10 seconds the value of 7 should be printed. Can you please explain on where I am going wrong?

Here is the jsfiddle

Alex Pan
  • 4,341
  • 8
  • 34
  • 45
zilcuanu
  • 3,451
  • 8
  • 52
  • 105

1 Answers1

6

You are calling callback(arg1, arg2) at the time genericFunction is being executed; its result 7 is being handed to setTimeout as the function to execute after 1 second (1000ms is not 10s). Since 7 is not a function, setTimeout will ignore it; but it will return a valid timer ID, and that is the result you are getting.

You must pass an unexecuted function into setTimeout. You could do setTimeout(callback, 1000) - but that would not be useful, as callback would be invoked after 1s without being passed any parameters, and its return value would be discarded. So the useful pattern is this:

var timer = setTimeout(function() {
  var result = callback(arg1, arg2);
  console.log("result is", result);
}, 1000);

(If you don't use clearTimeout, you can leave off var timer = bit.)

Also, note that you can never ever return a value from an asynchronously executed function (such as one executed by setTimeout). This answer explains why, and what to do instead.

Community
  • 1
  • 1
Amadan
  • 191,408
  • 23
  • 240
  • 301