You can use the operator %
(divide remainder) so that the index is always within the length
array, is a more mathematical solution and makes it always work because it depends on the size of the array.
The rest of division will always be a number between 0
and the divisor - 1
, that is to say, x % 5
will always be 0, 1, 2, 3 or 4.
Then just increment the index and use the rest 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">
This solves the specific problem, but a more interesting way to do this slide would be to add all the <img>
in a container, apply a CSS and go hide/show the other images. This way, when loading the page, all your images will be already downloaded and ready for use.
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"/>
<img src="https://via.placeholder.com/150/00ff00/ffffff"/>
<img src="https://via.placeholder.com/150/0000ff/ffffff"/>
<img src="https://via.placeholder.com/150/ff00ff/ffffff"/>
</div>
If only two images, and the indexes are 0 and 1, you can make a "toggle"
cont = !cont
– MarceloBoni
bad bro I’m half Nobb in these operators boto that cont=! cont in if or down?
– Leandro Lobo
The question before is, will only be two images?
– MarceloBoni
only two kk pq has q be more to work out?
– Leandro Lobo
Put the HTML code at least. So that we can create an interesting answer.
– João Pedro Schmitz
html is the <img> tag with src that is searching with Document.images
– Leandro Lobo
It would be interesting to put, because if it did not speak there would be no way to find out :|
– João Pedro Schmitz