简体   繁体   中英

Image Slider not working because of wrong delay Javascript

Below is my code for an image slider:

var slideIndex = 0;
var slides = document.getElementsByClassName("mySlides");
showSlides();
function showSlides() {    
    var i;    
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none"; 
    }
    slideIndex++;
    if (slideIndex> slides.length) {slideIndex = 1} 
    slides[slideIndex-1].style.display = "block"; 
    setTimeout(showSlides, 3000); // Change image every 5 seconds
}
function currentSlide(no) {
    var i;    
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none"; 
    }
    slideIndex = no;
    slides[no-1].style.display = "block";
}
function plusSlides(n) {
    var newslideIndex = slideIndex + n;
    if(newslideIndex < 4 && newslideIndex > 0){
        currentSlide(newslideIndex);
    }
}

Once an image is shown there is a delay of 3 seconds between each image. I have the ability to click a button to get on a specific image. What happens here is that the delay between images does not restart and sometimes I have 2 images shown in like half a second instead of 3.

How can I fix this?

<button class="w3-button w3-black w3-display-left" onclick="plusSlides(-1)">&#10094;</button>
<button class="w3-button w3-black w3-display-right" onclick="plusSlides(1)">&#10095;</button>
<br>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span> 
<span class="dot" onclick="currentSlide(2)"></span> 
<span class="dot" onclick="currentSlide(3)"></span>

Those are my buttons.

The timeout that is being called from your showSlides function will continue to tick on its own even if you click the buttons you have. You'll have to reset it manually on click. To do so, you need to do the following:

  1. Declare a variable like your slideIndex that will hold the timeout reference. This variable needs to be accessed by both showSlides and currentSlide :
var timeout = null;
  1. Store your timeout reference in that variable:
function showSlides() {    
    // rest of the code...

    timeout = setTimeout(showSlides, 3000);
}
  1. Clear the timeout and reset in your click handler:
function currentSlide(no) {
    // rest of the code...

    clearTimeout(timeout);
    timeout = setTimeout(showSlides, 3000);
}

This way, the timeout will run until the 3 seconds are reached or one of buttons is clicked, which will also reset it and another cycle is triggered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM