setInterval is not stopping in JavaScript

I want to make an automatic Image slider. And, when user hove over the image slider the auto slider will stop work and when leave the slide, then auto slide will start again.

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

But, when I am hovering its stop for the first time, but when again hovering its not stopping.

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

>Solution :

you reassign stopSliding to null after you start sliding again. just removed stopSliding = null; from mouseleave event.

Leave a Reply