user7167081 user7167081 - 1 year ago 142
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;

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].style.display = "block";

setTimeout(showSlides, 6000);

.hidden {
display: none;

<!DOCTYPE html>
<script src=""></script>
<meta charset="utf-8">
<link rel="stylesheet" href="lab5.css" media="screen" title="no title">
<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 class="hidden">
<h4 class="num" > 1 / 5 </h4>
<img src="">
<div class="hidden">
<h4 class="num"> 2 / 5 </h4>
<img src="">
<div class="hidden">
<h4 class="num"> 3 / 5 </h4>
<img src="">
<div class="hidden">
<h4 class="num"> 4 / 5 </h4>
<img src="">
<div class="hidden">
<h4 class="num"> 5 / 5 </h4>
<img src="">

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 Source

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


timer = setTimeout(showSlides, 6000);

So that you can cancel the timer where appropriate:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download