user3092778
user3092778

Reputation: 109

SetInterval keeps calling same function

I have this function:

original = 0;
original = original+1;
setInterval("dis"+original+"();", 2400);

But there is a problem, every time it is called it appears to be calling the same function over again... They're not calling individual functions.

Thanks for your help.

Upvotes: 0

Views: 694

Answers (2)

Jakob Hohlfeld
Jakob Hohlfeld

Reputation: 1564

It's because of the fact that original is used to construct the callback function name once - and only once - to call setInterval. As the name suggests, setInterval sets a callback once and continues executing until you clear the interval with clearInterval.

If you like to change the method beeing called, you could try setTimeout, i.e.:

var original = 0,
    cb = function() {
        ('dis' + original).prototype.call(null);
        original++;
        setTimeout(cb, 2400);
    }
cb();

Upvotes: 2

Matt Zeunert
Matt Zeunert

Reputation: 16561

You need to regenerate the function name every time as setInterval doesn't take care of that for you - it always runs the code that was passed to it when it was set up.

This will find the correct function in global scope (window) and call it:

original = 0;
original = original+1;
setInterval(function(){
    window["dis" + original]();
    original++;
}, 2400);

Incrementing the counter also needs to be done in the setInterval handler.

Upvotes: 3

Related Questions