Search code examples
javascriptcarouselsetinterval

How do i use setInterval for a carousel?


I'm trying to make my carousel autoplaying by using the setInterval function, but I've been getting no luck.

I tried calling the carousel function in setInterval function at the end, but its not working.. what did i do wrong?

Here is the sandbox https://codesandbox.io/s/slider-7ph05?file=/src/index.js

Here are my JS code:

const slides = document.querySelectorAll(".slide");
const prevBtn = document.querySelector(".prevBtn");
const nextBtn = document.querySelector(".nextBtn");

// Inline callback function
// forEach(function(element, index, array){ ... })
slides.forEach(function (slide, index) {
  slide.style.left = `${index * 100}%`;

  // console.log(slide);
  // console.log(index);
  // console.log(array);
});

let count = 0;
nextBtn.addEventListener("click", function () {
  count++;
  carousel();
});

prevBtn.addEventListener("click", function () {
  count--;
  carousel();
});

function carousel() {
  slides.forEach(function (slide) {
    if (count > slides.length - 1) {
      count = 0;
    }
    if (count < 0) {
      count = slides.length - 1;
    }

    slide.style.transform = `translateX(-${count * 100}%)`;
    // console.log(slides.length);
    // console.log(slide);
    // console.log(count);
  });
}

setInterval(carousel, 3000);

Solution

  • You don't seem to be incrementing the count variable in setInterval nor invoking the carousel function like you do, when the next or previous button is pressed. Update your setInterval to increment the counter and invoke the carousel function.

    setInterval(()=>{
    count++ //increment the counter
    carousel() //call the function
    }, 3000);
    

    Your index file should then look something like this:

    const slides = document.querySelectorAll(".slide");
    const prevBtn = document.querySelector(".prevBtn");
    const nextBtn = document.querySelector(".nextBtn");
    
    // Inline callback function
    // forEach(function(element, index, array){ ... })
    slides.forEach(function (slide, index) {
      slide.style.left = `${index * 100}%`;
    
      // console.log(slide);
      // console.log(index);
      // console.log(array);
    });
    
    let count = 0;
    nextBtn.addEventListener("click", function () {
      count++;
      carousel();
    });
    
    prevBtn.addEventListener("click", function () {
      count--;
      carousel();
    });
    
    function carousel() {
      slides.forEach(function (slide) {
        if (count > slides.length - 1) {
          count = 0;
        }
        if (count < 0) {
          count = slides.length - 1;
        }
    
        slide.style.transform = `translateX(-${count * 100}%)`;
        // console.log(slides.length);
        // console.log(slide);
        // console.log(count);
      });
    }
    
    setInterval(()=>{
      count++
      carousel()
    }, 3000);