I’m getting into Javascript functions with parameters taking functions as parameters. I understand passing parameters, but I’ve seen the following example, or examples like it:
// Callback Function Example
function greet(name, myFunction) {
console.log('Hello world');
// callback function
// executed only after the greet() is executed
myFunction(name);
}
// callback function
function sayName(name) {
console.log('Hello' + ' ' + name);
}
// calling the function after 2 seconds
setTimeout(greet, 2000, 'John', sayName);
It would seem to me you would call it:
setTimeout(greet('John', sayName), 2000);
But I’m pretty sure that is not right.
Can someone explain the reasoning of the parameter passing in that?
Thanks,
Russ
>Solution :
Please check the below link to have more deeper understanding of SetTimeout
setTimeout takes multiple parameters,
setTimeout(functionRef, delay, ...arguments )
functionRef : Function to be executed
delay: in milliseconds
arguments: can be any number of parameters which will passed to the function ref
https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
Example:
setTimeout((name,age,city)=>{alert(name+' '+age+' '+ city)},2000,"ABC","1","Dubai")