setInterval isn't repeating my code, but it runs once, I wonder why?

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

Answers


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

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 ];

Need Your Help

POCO support in ADO.NET Entity Framework?

entity-framework orm ado.net poco

I want to manually map my Entity Classes(POCO) to the Database tables usin ADO.NET Entity framework using the XML mapping file. Is it possible to do so, as I have heard there is no POCO support in ...

How to Auto fill a column using JavaScript?

javascript html css html-table

I am trying to create a check list. How is it possible to automatically fill the "Check List Status" column using JavaScript?