How can an inner function call a parent function after it has expired?
setTimeout(main, 2000);
function main(){
/* .... code */
setTimeout(console.log("hello after 5 seconds"), 5000);
}
The intended action is to print hello after 5 seconds in 5 seconds (7 total); with the above code it prints it in 2 seconds.
You need to pass
setTimeoutfunction references. WithsetTimeout(console.log("hello after 5 seconds"), 5000);, you callconsole.logimmediately. Any time you write()after a function name, you’re invoking it.console.logreturns undefined, which is what is passed tosetTimeout. It just ignores the undefined value and does nothing. (And it doesn’t throw any errors.)If you need to pass parameters to your callback function, there are a few different ways to go.
Anonymous function:
Return a function:
This works because invoking
loggersimply returns a new anonymous function that closes overmsg. The returned function is what is actually passed tosetTimeout, and when the callback is fired, it has access tomsgvia the closure.