Question

This is the code it runs perfectly once but setInterval does not repeat the second time or let's say the other consecutive times as it's suppose to, which is what I want, for example when it get's to last position of the array go back to first and so forth, can someone help me I greatly appreciate.

CSS:

#ok{position:absolute}

HTML:

<div id="ok">ok</div>

Script:

var a=[b(),c(),d()];

function b(){
for (var i=0;i<700000;i++){document.getElementById("ok").style.left=(i)+"px";}
alert(i);
};
function c(){
for (var i=0;i<20;i++){document.getElementById("ok").style.left=(i)+"px";};
alert(i);
}
function d(){
for (var i=0;i<5;i++){document.getElementById("ok").style.left=(i)+"px";alert(i)};
};
for(var i=0;i<a.length;i++){
setInterval(function(){a[i];if(i==a.length-1){i=0;};},1000);
}

Demo: jsfiddle

Was it helpful?

Solution

There are several problems with your code. First, you're executing b() c() and d() immediately rather than on each interval. Additionally, b() c() and d() are NOT causing any kind of animation, therefore the for loops are completely pointless. Then, your for loop at the end wrapping the interval is not necessary.

http://jsfiddle.net/EBhKp/1/

var a = [b, c, d];

function b() {
    document.getElementById("ok").style.left = 700000 + "px";
    console.log(700000);
}

function c() {
    document.getElementById("ok").style.left = 20 + "px";
    console.log(20);
}

function d() {
    document.getElementById("ok").style.left = 5 + "px";
    console.log(5);
}
var i = 0;
setInterval(function () {
    a[i]();
    i++;
    if (i == a.length) {
        i = 0;
    }
}, 1000);

A basic css transition will add the animation:

http://jsfiddle.net/EBhKp/2/

And here it is simplified:

var a = [700000, 20, 5];

function setLeftStyle(position) {
    document.getElementById("ok").style.left = position + "px";
    console.log(position);
}
var i = 0;
setInterval(function () {
    setLeftStyle(a[i]);
    i++;
    if (i == a.length) {
        i = 0;
    }
}, 1000);

OTHER TIPS

You must specify parameters when you use a function instead of use a local variable i.

Moreover, use a function pointer like this :

var a = [ b, c, d ];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top