0

I came across callback functions in JS and found it to be really amazing. Though there is something about how callbacks behave that i am not able to understand. Example:

function add(num1, num2){
  return num1 + num2;
}

function displaySum(num1, num2, callback){
  let a = callback(num1, num2)
  console.log(a);
}

setTimeout(displaySum(3,5,add), 3000); // This displays the result instantly

And in a similar case

function displayText(text){
    console.log('HEY JS');
}
setTimeout(displayText, 3000) //This seems to work

I am not able to understand why is this happening?

Tushar Roy
  • 1
  • 1
  • 16
  • `setTimeout()` expects a function as its first argument. You are passing it the return value of `displaySum()` (which is `undefined`) as you are calling `displaySum` rather than letting `setTimeout` call it for you. – Nick Parsons Feb 11 '22 at 06:35

1 Answers1

1

The issue is that you are directly calling the function inside the setTimeout. That function gets invoked and nothing is sent back.

setTimeout expects a function to be executed after the timer expires. You should only specify the referene to that function.

setTimeout(displaySum(3,5,add), 3000);

With the above statement you are instantly calling the displaySum function with 3 parameters. That is why you can see the result instantly. This function donot have a return value so there is no event that needs to be triggered after specified interval.

Replace that with

setTimeout(() => displaySum(3, 5, add), 3000);

Here the arraw function returns displaySum(3, 5, add), and this function will be called after specified interval.

function add(num1, num2) {
    return num1 + num2;
}

function displaySum(num1, num2, callback) {
    let a = callback(num1, num2)
    console.log(a);
}

setTimeout(() => displaySum(3, 5, add), 3000);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49