简体   繁体   English

图像 Slider 由于错误的延迟而无法工作 Javascript

[英]Image Slider not working because of wrong delay Javascript

Below is my code for an image slider:下面是我的图像 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.显示图像后,每张图像之间会有 3 秒的延迟。 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.这里发生的是图像之间的延迟不会重新启动,有时我会在半秒内显示 2 张图像而不是 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.即使您单击您拥有的按钮,从您的showSlides function 调用的超时将继续自行滴答。 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.声明一个变量,如您的slideIndex将保存超时参考。 This variable needs to be accessed by both showSlides and currentSlide : showSlidescurrentSlide都需要访问此变量:
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.这样,超时将一直运行,直到达到 3 秒或单击一个按钮,这也将重置它并触发另一个循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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