问题描述
问题是我的数组是 [[][][]] 而不是 [[]] :/
The issue was my array was [[][][]] instead of [[]] : /
这是我的剧本
function loopobject(array) {
var me = this;
this.array = array;
this.loop = function() {
counter = 0;
while(array.length > counter) {
window[array[counter]]('arg1', 'arg2');
counter++;
}
setTimeout(function(){ me.loop() }, 100);
}
}
var loopinstant = new loopobject(array);
window.onload = loopinstant.loop();
问题出现在第一次迭代之后.我不知道到底是什么问题,但我想知道是不是因为它在一个对象内部,一旦函数被重新创建,它就不会记住数组?
The problem arises after the first iteration. I don't know exactly the problem but I'm wondering if its due to the fact this is inside an object, and once the function is recreated it doesn't remember the array?
推荐答案
不要将字符串传递给 setTimeout
.
Don't pass a string to setTimeout
.
将字符串传递给 setTimeout
会导致它在全局范围内被 eval
ed.
除了不必要的缓慢之外,这意味着它不会看到您的局部变量,包括 loop
变量.
Passing a string to setTimeout
causes it to be eval
ed in global scope.
In addition to being needlessly slow, that means that it won't see your local variables, including the loop
variable.
相反,您应该将函数本身传递给 setTimeout
:
Instead, you should pass a function itself to setTimeout
:
setTimeout(function() { loop(array); }, 100);
此外,loopobject
实际上没有您可以稍后调用的 loop
属性.
要创建一个属性,请将其更改为 this.loop = function(...) { ... }
.
Also, the loopobject
doesn't actually have a loop
property that you can call later.
To make a property, change it to this.loop = function(...) { ... }
.
请注意,setTimeout
回调不会使用正确的 this
调用.
您还需要在局部变量中保存 this
的副本.
Note that the setTimeout
callback won't be called with the correct this
.
You'll also need to save a copy of this
in a local variable.
最后,您的 window.onload
代码将调用 loop
,然后将结果分配给 onload
.
Finally, your window.onload
code will call loop
, then assign the result to onload
.
纠正这些问题,你的代码就变成了
Correcting these issues, your code turns into
function loopobject(){
var me = this;
this.loop = function(array){
counter = 0;
while(array.length > counter){
window[array[counter]]('arg1', 'arg2');
counter++;
}
setTimeout(function() { me.loop(array); }, 100);
};
}
var loopinstant = new loopobject();
window.onload = function() { loopinstant.loop(array); };
这篇关于setTimeout 没有被调用(?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!