Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Callback function behaviour in JS

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading