July 5, 2013
how to assign window.setTimeout to dynamic variable?
Tomas Šivickas’s Question:
I need to assign window.setTimeout to dynamically made GLOBAL vars or objects, something like:
$n = 1
var variable[$n] = window.setTimeout( function () { /*somecode*/ },2000)
This isn’t working.
Also not working:
var eval(variable+$n) = window.setTimeout( function () { /*somecode*/ },2000)
But works without “var”, but I need global variable so I need with “var” scope.
What could be possible solution?
To address a global variable, you should not use var
. Using var
redefines the variable in that scope.
Let me explain to you with a different example:
var i = 2;
function show() {
alert(i); // This will show 2
}
But in this example:
var i = 2;
function show() {
var i = 4; //This defines a local variable called "i" to be used inside function only
alert(i); // Will show 4;
}
alert(i); // But this will still show 2
So, use it without the var
$n = 1
variable[$n] = window.setTimeout( function () { /*somecode*/ },2000)