In javascript, what is the scope of the variables used in setTimeout?

I use the following code in a function:

setTimeout("doSomething(var1)",10000); 

But I also have var1 available as a global variable. After 10,000 milliseconds will it call local var1 or global var1 ?

+7
source share
2 answers

It:

 setTimeout('doSomething(var1)', 10000); 

will pass the global variable var1 ,

And this:

 setTimeout(function() { doSomething(var1); }, 10000); 

will pass the local variable var1 .

Live demo: http://jsfiddle.net/simevidas/EQMaz/

+15
source

It will pass a global variable named var1 .

+3
source

All Articles