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?
>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);