Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 226
Salman Virk Avatar asked Apr 25 '11 14:04

Salman Virk


People also ask

What are the scopes of a variable in JavaScript?

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.

What is the use of setTimeout () in JavaScript?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

Does setTimeout return value?

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.

What is the default value of setTimeout?

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.


1 Answers

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/

like image 106
Šime Vidas Avatar answered Sep 30 '22 22:09

Šime Vidas