user7167081 user7167081 - 4 months ago 27
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>
<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="image1.jpg" >
<div class="hidden">
<h4 class="num"> 2 / 5 </h4>
<img src="image2.jpg" >
<div class="hidden">
<h4 class="num"> 3 / 5 </h4>
<img src="image3.jpg" >
<div class="hidden">
<h4 class="num"> 4 / 5 </h4>
<img src="image4.jpg">
<div class="hidden">
<h4 class="num"> 5 / 5 </h4>
<img src="image5.jpg" >

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


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. :)


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.