In Javascript, what is the scope of variables used in setTimeout? - Stack Overflow

admin2025-02-19  9

I am using the following code in a function:

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

But, I also have var1 available as global variable. After 10000 milliseconds, will it call the local var1 or the global var1?

I am using the following code in a function:

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

But, I also have var1 available as global variable. After 10000 milliseconds, will it call the local var1 or the global var1?

Share Improve this question edited Apr 25, 2011 at 14:51 Donut 113k20 gold badges135 silver badges147 bronze badges asked Apr 25, 2011 at 14:50 Salman VirkSalman Virk 12.3k9 gold badges38 silver badges47 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 15

This:

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/simevidas/EQMaz/

It will pass the the global variable named var1.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1739977462a113781.html

最新回复(0)