最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to stop interval in js? - Stack Overflow

programmeradmin1浏览0评论

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)
    }
}

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)
    }
}

Share Improve this question asked Dec 3, 2021 at 10:21 Adrian KatoAdrian Kato 1131 gold badge2 silver badges8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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./jsref/met_win_clearinterval.asp

The setInterval method returns a pointer to that interval, you then just pass it to the clearInteral

const interval = setInterval(() => {
    console.log('inside interval');
}, 500);

setTimeout(() => clearInterval(interval), 2000)

setInterval return an identifier which allow you to clear the interval

let myInterval;

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

myInterval = setInterval(addPositionRight, 10);
发布评论

评论列表(0)

  1. 暂无评论