Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop interval in js?

At the moment I'm trying to create a slideshow for pictures (when arrow is clicked, another picture slides in, all pictures are in a row in html). I'm not using scroll method. Images are moving, but seems like I can't stop the interval. I wanted to ask how to stop the interval? What is something that I'm missing?

const icons = document.querySelectorAll(".icons i");
const imageDiv = document.querySelector(".imageDiv");

let positionRight = 0;

function addPositionRight () {
    positionRight += 1;
    imageDiv.style.right = `${positionRight}%`;
}

icons[1].onclick = () => {
    setInterval(addPositionRight, 10);
    if (positionRight === 100) {
        clearInterval(addPositionRight)
    }
}
like image 378
Adrian Kato Avatar asked Dec 10 '25 04:12

Adrian Kato


1 Answers

You have to use clearInterval method as follow,

const stopInterval = setInterval(addPositionRight, 10);

clearInterval(stopInterval) //<----- use it where you want to stop it.

more information: https://www.w3schools.com/jsref/met_win_clearinterval.asp

like image 141
Nikhil Shah Avatar answered Dec 12 '25 04:12

Nikhil Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!