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
?
JavaScript variables have only two scopes. Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
The setTimeout() returns a timeoutID which is a positive integer identifying the timer created as a result of calling the method. The timeoutID can be used to cancel timeout by passing it to the clearTimeout() method.
First of all, the setTimeout JavaScript method should contain the function that you intend to apply. The second parameter sets a time when the specified function is to be called. However, it is optional, and the default value is 0.
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.net/simevidas/EQMaz/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With