小编典典

setInterval 没有在 JavaScript 中停止

all

我想做一个自动图像滑块。而且,当用户将鼠标悬停在图像滑块上时,自动滑块将停止工作,当离开幻灯片时,自动滑块将再次开始。

 <div class="slider-wrapper">
        <ul class="slider">
            <li>
                <img src="https://cdn.pixabay.com/photo/2022/07/31/20/32/vintage-bus-7356817_960_720.jpg" alt="">
            </li>
            <li>
                <img src="https://cdn.pixabay.com/photo/2022/04/20/00/09/flowers-7143991_960_720.jpg" alt="">
            </li>
            <li>
                <img src="https://cdn.pixabay.com/photo/2022/03/26/15/17/cornelian-cherry-7093063_960_720.jpg" alt="">
            </li>
            <li>
                <img src="https://cdn.pixabay.com/photo/2013/08/20/15/47/poppies-174276_960_720.jpg" alt="">
            </li>
            <li>
                <img class="image" src="https://cdn.pixabay.com/photo/2022/07/25/16/41/child-7344169_960_720.jpg"
                    alt="">
            </li>
            <li>
                <img src="https://cdn.pixabay.com/photo/2021/08/08/22/41/flowers-6532105_960_720.jpg" alt="">
            </li>
        </ul>
    </div>
const slider = document.querySelector(".slider");
const sliderWrapper = document.querySelector(".slider-wrapper");

let currentSlide = 0;

function nextSlide(slide) {
  Array.from(slider.children).forEach((item, index) => {
    item.style.transform = `translateX(${100 * (index - slide)}%)`;
  });
}

nextSlide(0); // initial slide on mounted

var stopSliding = null;

function startAutoSliding() {
  stopSliding = setInterval(() => {
    console.log("Next Clicked");
    currentSlide++;
    if (currentSlide >= 0 && currentSlide < slideLength) {
      nextSlide(currentSlide);
    } else {
      currentSlide = 0;
      nextSlide(currentSlide);
    }
    console.log(currentSlide);
  }, 4000);
}

sliderWrapper.addEventListener("mouseover", (event) => {
  console.log("mouseover");
  event.stopPropagation();
  clearInterval(stopSliding);
});

sliderWrapper.addEventListener("mouseleave", (event) => {
  event.stopPropagation();
  console.log("mouseleave");
  startAutoSliding();
  stopSliding = null;
});
startAutoSliding();

但是,当我第一次悬停它的停止时,但是当再次悬停时它没有停止。

StackBlitz:https ://stackblitz.com/edit/js-gqgyjj?file=index.html


阅读 103

收藏
2022-08-05

共1个答案

小编典典

再次开始滑动后重新分配stopSliding为 null 。刚刚stopSliding = null;mouseleave事件中删除。

2022-08-05