You don’t want to use any looping structure like for
or while
. Instead just make a function that gets invoked with the index to start it off, and then inside the callback, it increments the index and recursively invokes the same function. when the index gets to 3
, set it back to 0
before the recursive call.
function cycle(index) {
setTimeout(function() {
document.getElementById(location[index]).style.background = color[index];
index++; // Increment the index
if (index >= 3) {
index = 0; // Set it back to `0` when it reaches `3`
}
cycle(index); // recursively call `cycle()`
//cycle(++index % 3);
}, 1000);
}
cycle(0);
I used the %
operator for a quick way to make sure it gets set back to 0
on the recursive call.
8
solved Javascript for loop (How to make it repeat forever) [closed]