setTimeout is not being called(?)

本小妞迷上赌 提交于 2019-12-13 02:17:47

问题


The issue was my array was [[][][]] instead of [[]] : /

This is my Script

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?


回答1:


Don't pass a string to setTimeout.

Passing a string to setTimeout causes it to be evaled in global scope.
In addition to being needlessly slow, that means that it won't see your local variables, including the loop variable.

Instead, you should pass a function itself to setTimeout:

setTimeout(function() { loop(array); }, 100);

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(...) { ... }.

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.

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); };



回答2:


Replace

setTimeout("loop()", 100);

with

setTimeout(function() { loop(array); }, 100);


来源:https://stackoverflow.com/questions/4536266/settimeout-is-not-being-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!