Say I have a simple function that alerts a message:
function callMessage(msg){
alert(msg);
}
Now when I call it like so, it does not work. Throws error “hey is not defined”
function sayHi(){
var hey = "hi there"
setTimeout("callMessage(hey)", 1000);
}
sayHi();
But when I call it inside an anonymous function it does work:
function sayHi(){
var hey = "hi there"
setTimeout(function(){callMessage(hey);}, 1000);
}
sayHi();
Why is the “hey” variable only visible when I put it inside an anonymous function?
In the first example, the code is evaluated after the timer expired and the current scope was left.
heyis undefined at that moment.The second example – the proper way to use
setTimeout– uses an anonymous function created when invokingsetTimeout(). This anonymous function also receives a copy of the current scope.