You can use the %
(division remainder) operator so that the index is always within length
of the array, it is a more mathematical solution and always works because it depends on the size of the array.
The remainder of the division will always be a number between 0
and divisor - 1
, that is, x % 5
will always be 0, 1, 2, 3 or 4.
Then simply increment the index and use the remainder of the division to create a cycle.
for(let i=0 ; i < numero_qualquer ; i++) {
console.log(i % 5);
}
// Printa: 0,1,2,3,4,0,1,2,3,4,0,1,...
var imagens = [
'https://via.placeholder.com/150/ff0000/ffffff',
'https://via.placeholder.com/150/00ff00/ffffff',
'https://via.placeholder.com/150/0000ff/ffffff',
'https://via.placeholder.com/150/ff00ff/ffffff',
];
var img = document.getElementById('imagem');
var i = 0;
var l = imagens.length;
function slide() {
i = (i + 1) % l;
img.src = imagens[i];
}
setInterval(slide, 2000);
<img id="imagem" src="https://via.placeholder.com/150/ff0000/ffffff">
Thissolvestheprobleminspecific,howeveramoreinterestingwaytodothisslidewouldbetoaddallthe<img>
inacontainer,applyaCSSandgohide/showtheotherimages.Thisway,whenyouloadthepage,allyourimageswillalreadybedownloadedandreadytouse.
Ex:
var container = document.getElementById('container');
var i = 0;
var imgs = container.querySelectorAll('img');
var l = imgs.length
function slide() {
imgs[i].classList.remove('active');
i = (i + 1) % l;
imgs[i].classList.add('active');
}
setInterval(slide, 2000);
#container {
position: relative;
}
#container > img {
position: absolute;
opacity: 0;
transition: opacity 500ms linear;
}
#container > img.active {
opacity: 1;
}
<div id="container">
<img class="active" src="https://via.placeholder.com/150/ff0000/ffffff"/><imgsrc="https://via.placeholder.com/150/00ff00/ffffff"/>
<img src="https://via.placeholder.com/150/0000ff/ffffff"/><imgsrc="https://via.placeholder.com/150/ff00ff/ffffff"/>
</div>