1

guys i've been trying to solve this for the last couple of days. I really need your help and I want to understand whats going on. My Function will iterate once and the go back to the first value, how can I make it so that the loops starts from zero and keeps on looping. I've tried while loops but thos attempts have been unsuccessful. Thank you guys!

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);
    };
}
Anis R.
  • 6,656
  • 2
  • 15
  • 37
aromano108
  • 31
  • 1

1 Answers1

2

What you probably want is a setInterval. Unlike setTimeout that only executes once, setInterval executes at every interval of time (e.g. every 1 sec) until you call clearInterval().

Using this and some modulo (%) logic, we can do:

var currentImage = 0;

//this will call `changeBackground` every 1 second
setInterval(changeBackground, 1000); //1000 ms = 1 sec

function changeBackground() {
    currentImage = (currentImage + 1) % imgArray.length;
    imgContainer.style.background = imgArray[currentImage];
}

Explanation of the modulo part:

The % or modulo gives us the remainder of the Euclidean division of imgArray.length by currentImage + 1, which will always be a value between 0 and imgArray.length - 1. Whenever currentImage + 1 becomes equal to imgArray.length, currentImage gets reset to zero.

Anis R.
  • 6,656
  • 2
  • 15
  • 37