user7167081 user7167081 - 19 days ago 5
CSS Question

automatic and manual slideshow javascript

I have to make a slideshow that has to work both automatic and manual. For the manual part i have two buttons: next and previous that allows me to see the photos without having to wait a certain period of time between images. When i don't click on the bottons, the slideshow goes automatic and the images change after 6 seconds (for example). My problem is that, after I click on the previous/ next button, the images start to appear faster or they appear more than one on the screen. Here is the code I am working with:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<meta charset="utf-8">
<title>jQuery</title>
<link rel="stylesheet" href="lab5.css" media="screen" title="no title">
</head>
<body>
<h1 class="titlu">Goodies</h1>
<div align="center">
<button class="button" onclick="plusSlides(-1)" >Previous</button>
<button class="button" onclick="plusSlides(1)" >Next</button>
</div>
<div class="hidden">
<h4 class="num" > 1 / 5 </h4>
<img src="image1.jpg" >
</div>
<div class="hidden">
<h4 class="num"> 2 / 5 </h4>
<img src="image2.jpg" >
</div>
<div class="hidden">
<h4 class="num"> 3 / 5 </h4>
<img src="image3.jpg" >
</div>
<div class="hidden">
<h4 class="num"> 4 / 5 </h4>
<img src="image4.jpg">
</div>
<div class="hidden">
<h4 class="num"> 5 / 5 </h4>
<img src="image5.jpg" >
</div>
<script>

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
showSlides(slideIndex += n);
}

function showSlides(n) {
var i;
var slides = document.getElementsByClassName("hidden");

if (n===undefined){n= ++slideIndex;}
if (n > slides.length) {slideIndex = 1;}
if (n < 1) {slideIndex = slides.length}

$(slides[slideIndex-1]).fadeIn(2000);
slides[slideIndex-1].style.display = "block";
$(slides[slideIndex-1]).delay(3000);
$(slides[slideIndex-1]).fadeOut(1000);

setTimeout(showSlides, 6000);
}

</script>
</body>
</html>


The css for the .hidden class is:

.hidden {
display: none;
}


Is there a way I can make the slideshow return to its "speed" of showing the images every 6 seconds after I click on previous/next? And also to solve that problem with showing more than 1 image at a time?

Thanks. :)

Answer

What's happening is that you are causing multiple timers to be started, which causes your callback function to run more often than it should.

You need to make sure that you capture the integer that is returned from your timer:

var timer = null; // Do this in a scope that is accessible to all your relevant functions

...then:

timer = setTimeout(showSlides, 6000);

So that you can cancel the timer where appropriate:

clearTimeout(timer);

You will want to clear your timer upon the clicking of the button, which will stop the automatic one from running and then you can start a new one, leaving you with only one running timer.

Comments