I'm trying to make an automatic slideshow in css and js. I've got a function that infinitely loops through an array of images (in the slideshow) after a specified time.
function autoSlide(){
carouselSlide.style.transition = "transform 1s ease-in-out";
counter++;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
t = setTimeout("autoSlide()", time);
}
But I want to reset the timer time
if I manually change the slide by pressing a button. I tried this but it didn't work:
function autoSlide(){
carouselSlide.style.transition = "transform 1s ease-in-out";
counter++;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
nextBtn.addEventListener('click',()=>{
clearTimeout(t);
})
t = setTimeout("autoSlide()", time);
}
Any help would be much appreciated.
Thanks.
Please use setInterval
instead of setTimeout
.
Like this:
function autoSlide(){
carouselSlide.style.transition = "transform 1s ease-in-out";
counter++;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
var t = setInterval(autoSlide, time)
nextBtn.addEventListener('click',()=>{
clearInterval(t);
t= setInterval(autoSlide, time)
})