-1

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

2

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.