1

我需要将 window.setTimeout 分配给动态生成的 GLOBAL 变量或对象,例如:

$n = 1
var variable[$n] = window.setTimeout( function () { /*somecode*/ },2000)

这是行不通的。
也不工作:

var eval(variable+$n) = window.setTimeout( function () { /*somecode*/ },2000)

但是没有“var”也可以工作,但是我需要全局变量,所以我需要使用“var”范围。

有什么可能的解决方案?

4

3 回答 3

1

你可以像这样实现

variable = [];

variable[1] = window.setTimeout( function () { alert('hi') }, 2000);

// This will alert 'hi' in 2 seconds 

或者如果你想能够打电话setTimeoutfunction你可以这样做

variable = [];

variable[1] = function(){ window.setTimeout( function () { alert('hi') },2000) };

// This won't alert 'hi' until you do this 

variable[1]();

您遇到的问题是,variable如果array您想按照自己的方式进行操作,则必须首先制作variable一个array这样的全球性产品?只需删除var

$n = 1
variable = [];
variable[$n] = window.setTimeout( function () { alert('hi') },2000);
于 2013-07-05T09:06:29.887 回答
0

要寻址全局变量,您不应使用var. 使用var重新定义该范围内的变量。

让我用一个不同的例子向你解释:

var i = 2; 

function show() {
   alert(i); // This will show 2
}

但在这个例子中:

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

所以,使用它没有var

$n = 1
variable[$n] = window.setTimeout( function () { /*somecode*/ },2000)
于 2013-07-05T09:01:52.040 回答
0

不确定您是要引用 setTimeout 还是使用代码执行 setTimeout,也许这会给您一个想法:

window.myvar = function(){window.setTimeout( function () { alert("hi"); },2000)};
myvar();// will alert hi after 2 seconds

如果你需要传递一个变量:

window.myvar = function(message){
  window.setTimeout( function () { alert(message); },2000)
};
myvar("bye");// will alert bye after 2 seconds

setTimeout 是一个函数,将返回一个数字,您可以使用该数字取消超时,以下不会提醒任何事情,因为我取消了它:

var timeoutHandle=setTimeout(function(){alert("hi");},5000);
// next line cancels the timeout
clearTimeout(timeoutHandle);
于 2013-07-05T09:04:48.500 回答