Wayneio
Wayneio

Reputation: 3566

Javascript (Jquery) Loop not working

this is my first post on the forum. Here i have a javascript attempting to loop, and to set each element as an active class, then wait, remove the class and add it to the next element. My problem is that it does the first one, then no more...

var i = 1;

function myLoop() {
    setTimeout(function() {
        var i = 1;
        var j = (i - 1);

        $("#nH" + j).removeClass("active");
        $("#nH" + i).addClass("active");

        i++;
        if (i < 5) {
            myLoop();
        }
    }, 3000)
}

myLoop();​

Upvotes: 2

Views: 182

Answers (4)

xdazz
xdazz

Reputation: 160843

Here is a solution without using loop and global variable. The example.

setInterval((function(min, max){
    var i = min;
    return function() {
        $("#nH"+i).addClass("active");
        $("#nH"+(i===min ? max : i-1)).removeClass("active");
        if (++i > max ) i = min;
    }
})(0, 4), 1000);

Upvotes: 0

Sid
Sid

Reputation: 7631

I believe it is because you are assigning i equal to 1 and therefor it is removing the class of the same element again and again. So it is actually being called multiple times but you don't realize as the effect is the same. Problem is with your logic with the variable i and j. Try this.

var i = 1;

function myLoop() {
    setTimeout(function() {

        var j = (i - 1);

        $("#nH" + j).removeClass("active");
        $("#nH" + i).addClass("active");

        i++;
        if (i==5)
           i=1;
        if (i < 5) {
            myLoop();
        }
    }, 3000)
}

myLoop();​

Upvotes: 1

mgraph
mgraph

Reputation: 15338

remove var i = 1; before var j = (i - 1); and add it here

  if (i < 5) {
     i=1;
     myLoop(); 

  } 

Upvotes: 3

mpm
mpm

Reputation: 20155

because you need to call setTimeout again in your loop

var i = 1;                    

function myLoop () {       

    var j = (i-1);

$("#nH" + j).removeClass("active");
$("#nH" + i).addClass("active");

    i++;
  if (i < 5) {        
     return setTimeout(myLoop,3000); /// <- HERE       
  }                   
}

setTimeout(myLoop,3000); 

Upvotes: -1

Related Questions