Sam
Sam

Reputation: 13

setTimeout is not being called(?)

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?

Upvotes: 1

Views: 4494

Answers (2)

SLaks
SLaks

Reputation: 887225

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

Upvotes: 2

cdhowie
cdhowie

Reputation: 168958

Replace

setTimeout("loop()", 100);

with

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

Upvotes: 0

Related Questions