2

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 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I already modified this as you suggest. Now it goes all the way to the end of the img array and after that it goes to the first img. How can I get the for loop to get going after arriving to the first value again?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.