Conditional Statements Array Looping

Viewed 51

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';
}

3 Answers

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

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.

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

Related