I need help getting my image slideshow to work properly. I set it up to loop over an array of images and display each one in 5 second intervals. What it actually does is loop over the entire array but only displays the last image. Code below:
const imgArray = ['http://media.tumblr.com/tumblr_lf88gg6J5d1qamm7n.jpg',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR5SG1QIHcwLM9FNPFOO0IvFBNJ9CJCGZ-iGz7zfmfhTypEqqTU','https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQRZLiRBwwBBMAapL5IzxqoV-zskYuGD9lWvyirUryKjVaRqwlO'];
let index = 0;
function autoChange() {
let img = document.getElementById('img');
let arrayIndex;
for (arrayIndex = 0; arrayIndex < imgArray.length; arrayIndex++) {
img.src = imgArray[arrayIndex];
setTimeout(autoChange, 3000);
console.log(imgArray[arrayIndex]);
}
arrayIndex++;
if(arrayIndex > imgArray.length) {
arrayIndex = 0
};
}
autoChange();
<section>
<figure>
<img id='img' class='displayed-img' width="350" src="imgs/pic0.jpg">
</figure>
</section>
Thank you.
autoChange()request you are looping over all the images, which in turn leads to all the images being loaded very quickly but ending on the last one. And this is what you are seeing. What you need to do is keep track of the image that is load, check for the next one and load that. If no next image, go back to the start (hint: no loop needed).setTimeoutto be blocking, meaning it’ll wait the three seconds before continuing with the next iteration, which it will not.indexis never actually used in the OPs code beyond initializing it to0so it will stay0the entire time.arrayIndexwill become 3 almost immediately (not after 3 seconds).