I am looking to create a slideshow in which the user can click to the next slide and also that the slideshow will automatically move to the next slide if no click
takes place.
I have created the below code and if no click is made for 5 seconds it automates to the next slide with no problem, however the issue is that when the prev next button is clicked
the slides start randomly automating within less of a second of each other??
I have looked online for the solution to this but there are no clear answers :(
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
if (n == undefined) {
n = ++slideIndex
}
if (n > slides.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = slides.length
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slideIndex - 1].style.display = "block";
setTimeout(showSlides, 5000)
}
.mySlides {
display: none;
}
.prev,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -120px;
padding-left: 10px;
padding-right: px;
padding-bottom: 10px;
color: #A371D1;
font-weight: bold;
font-size: 60px;
transition: 0.5s ease;
border-radius: 0 15px 15px 0;
}
.next {
right: 0px;
border-radius: 15px 0px 0px 15px;
}
.prev:hover,
.next:hover {
background-color: white;
}
<div id="slideShowContainer">
<div class="mySlides fade3">
<img class="homePageSlides" id="slidePic1" src="Purplelimetree-images/HomePage/aboutUs6.jpg">
</div>
<div class="mySlides fade3">
<img class="homePageSlides" src="Purplelimetree-images/HomePage/manLookinAtTreeHouse.jpg">
</div>
<a class="prev" onclick="plusSlides(-1)">‹</a>
<a class="next" onclick="plusSlides(1)">›</a>
</div>
Your timeout needs to be cleared when user is interacting with the buttons. Without clearing the timeout, it will run by itself regardless of human interaction and it will mess up your slide index.
Your original code would not of worked properly for any of the buttons because your times will start triggering after 5 seconds and since you never clear them, it will trigger as many times as you click the buttons
https://jsfiddle.net/tssqtdp7/