Klye Klye - 5 months ago 39
CSS Question

JS Creating a Timer To Hide Image Slideshow

I'm trying to create a image slideshow that plays through all of the images and on the last one fade away and no longer show any images for another 10 seconds, then after 10 seconds it starts all over again. Currently I have it stopping on the last image but it doesn't do anything after that and just gets stuck. Not really all that sure on how to accomplish something like this so any and all help is really appreciated! Below is the JS if any other script is needed please let me know!

var slideIndex = 0;
showSlides();

function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
// var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex >= slides){
setTimeout(function(){ slideIndex = 1; }, 10000);
}
/*for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}*/
slides[slideIndex-1].style.display = "block";
//dots[slideIndex-1].className += " active";
setTimeout(showSlides, 10000); // Change image every 10 seconds
}


UPDATE: setInterval

var slideIndex = 0;
showSlides();

var myPause = setInterval(function(){ showSlides() }, 10000);

function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {
myPause;
slideIndex = 1;
}
slides[slideIndex-1].style.display = "block";
setTimeout(showSlides, 10000); // Change image every 10 seconds
clearInterval(myPause);
}

Answer

As BillyNate already said, setInterval makes it work the way you want. To repeat the slideshow with a 10 second break inbetween, you need to hide the last slide and then repeat the slideshow after 10 seconds by setting a timeout.

The animation can be applied where the last images gets set to display: none.

var slides = document.getElementsByClassName("mySlides");

function switchSlides() {
  var slideCount = slides.length;
  var i = 0;
  
  // Set first slide visible
  slides[i].style.display = "block";
  
  // Switch slide every 10 seconds
  var switchInterval = setInterval(function() {
    i++;
    if (i < slideCount) {
      slides[i-1].style.display = "none";
      slides[i].style.display = "block";
    } else {
      clearInterval(switchInterval);

      // Hide last slide (--> fade out image)
      slides[i-1].style.display = "none";
      
      // Wait 10 seconds, then repeat switchSlides
      setTimeout(switchSlides, 10000);
    }
  }, 10000);
}

switchSlides();
.mySlides {
  display: none;
}
<img class="mySlides" src="http://unsplash.it/200?image=10">
<img class="mySlides" src="http://unsplash.it/200?image=20">
<img class="mySlides" src="http://unsplash.it/200?image=30">