user7167081 user7167081 - 24 days ago 7
CSS Question

Automatic and manual slideshow

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 buttons, the slideshow goes automatic and the images change after six 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:



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);
}

.hidden {
display: none;
}

<!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="http://placehold.it/150x150?text=1">
</div>
<div class="hidden">
<h4 class="num"> 2 / 5 </h4>
<img src="http://placehold.it/150x150?text=2">
</div>
<div class="hidden">
<h4 class="num"> 3 / 5 </h4>
<img src="http://placehold.it/150x150?text=3">
</div>
<div class="hidden">
<h4 class="num"> 4 / 5 </h4>
<img src="http://placehold.it/150x150?text=4">
</div>
<div class="hidden">
<h4 class="num"> 5 / 5 </h4>
<img src="http://placehold.it/150x150?text=5">
</div>
</body>
</html>





Is there a way I can make the slideshow return to its "speed" of showing the images every six seconds after I click on previous/next?

Also, how can I prevent it from showing more than one image at a time?

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.