aromano108
aromano108

Reputation: 31

Conditional Statements Array Looping

I'm trying to create an image slider for a website, I want to learn why my array won't go back to zero after finishing the first iteration and keep on iterating. I want the slider to iterate on and on automatically.

function run() {
  for (let i = 0; i < imgArray.length; i++) {
    (function(e) {
      setTimeout(function() {
        if (i == imgArray.length) {
          i = 0;
        }

        imgContainer.style.background = imgArray[i];
      }, 3000 * e);
    })(i);
  };
  imgContainer.style.height = '100vh';
}

Upvotes: 2

Views: 87

Answers (3)

Mureinik
Mureinik

Reputation: 311498

The condition i == imgArray.length inside the loop is never true, since the loop runs until i < imgArray.length. You could use <= instead as Ali Abug Hijleh suggested, but I think it would be easier to maintain if you explicitly show the loop should run forever with while (true) and use the % operator to get the right index:

function run() {
  let i = 0;
  while (true) {
    (function(e) {
      setTimeout(function() {
        imgContainer.style.background = imgArray[i % imgArray.length];
      }, 3000 * e);
    })(i);
  };
  imgContainer.style.height = '100vh';
  ++i;
}

Upvotes: 2

TSR
TSR

Reputation: 20446

That's because your for loop ends before you reset it to zero because you reset it to zero inside a setTimeout

Upvotes: 0

Dzmitry Kushnarou
Dzmitry Kushnarou

Reputation: 566

i will never reach the imgArray.length because the loop only works when i is less than imgArray.length (since you use i < imgArray.length as the condition)

Try if (i == imgArray.length -1) { ... } instead.

Upvotes: 1

Related Questions