Please refer to my below code:
//Principal Function
function greet3(name, sayName) {
document.getElementById("jac3").innerHTML = "Hello " + name;
sayName(name);
};
//Callback Function
function sayName(name) {
document.getElementById("jac3").innerHTML += ". How are you? " + name;
}
//Calling the function after 10 seconds
greet3("Neha", setTimeout(sayName,3000));
//greet3("Neha", sayName);
<p id="jac3"></p>
When I use setTimeout function,
greet3("Neha", setTimeout(sayName,3000));
the output of name gets undefined.
Please help me with correct syntax.
When you write setTimeout(param1, param2) you are executing the function due to the parenthesis.
//Principal Function
function greet3(name, callback, timeout) {
document.getElementById("jac3").innerHTML = "Hello " + name;
setTimeout(() => callback(name), timeout);
};
//Callback Function
function sayName(name) {
document.getElementById("jac3").innerHTML += ". How are you? " + name;
}
//Calling the function after 3 seconds
greet3("Neha", sayName, 3000);
<p id="jac3"></p>