ClearInterval() 虽然带 ID 不起作用

问题描述 投票:0回答:2

当使用 SetInterval 重复使用 2 个函数显示和删除计时器时,我有一个代码。但是,当计时器完成时,我尝试使用 ClearInterval 清除 SetInterval 但这不起作用。当 setInterval 和 ClearInterval 在 gettimer 函数之外设置时,它们也可以正常工作。有人可以帮忙吗?

let M1, M2
function ShowScrollBar(){
    ScrollContainer.classList.add('show-scroll-container')
}

function TimeShowscrollBar(){
    M1 = setInterval(ShowScrollBar,3000)
}

function RemoveScrollBar(){
    ScrollContainer.classList.remove('show-scroll-container')
}

function TimeRemovecrollBar(){
    M2 = setInterval(RemoveScrollBar,6000)
}

function ClearTimeShowscrollBar(){
    clearInterval(M1)
}

function ClearTimeRemovecrollBar(){
    clearInterval(M2)
}

function gettimer(){
const futureTimems = ClosingDate.getTime()
const presentTimems = new Date().getTime()
const RemainingTimeSec = (futureTimems-presentTimems)/1000
if(RemainingTimeSec>=0){    
    window.addEventListener('DOMContentLoaded', function(){
        popup.classList.add('showpopup')
        popup.classList.remove('popup')
       
    })
}

ClosePopupBtn.addEventListener('click',function(){
    popup.classList.remove('showpopup')
    popup.classList.add('popup')
    TimeShowscrollBar()
    TimeRemovecrollBar()
       
})

if (RemainingTimeSec<=0){
    clearInterval(countdown)
//Functions with clearInterval not working here
    ClearTimeShowscrollBar()
    ClearTimeRemovecrollBar()
    timing.forEach(function(contenu, MVindex){
        contenu.innerHTML = '00'
    })
    timingS.forEach(function(contenu, MVindex){
        contenu.innerHTML = '00'
    })
    popup.classList.remove('showpopup')
    popup.classList.add('popup')  
}
}
let countdown = setInterval(gettimer,1000)
gettimer()
javascript setinterval clearinterval
2个回答
1
投票

这里发生的事情很多,会导致很多问题。

问问自己,如果用户单击“关闭”按钮两次会发生什么?三次?每次点击它都会调用

setInterval
,但也许将来您只能清除其中一个。

那么,如果多次调用

addEventListener
会发生什么呢?您创建了多个侦听器,因此单击按钮就像被单击了多次一样。

最好的情况是,当倒计时为零时,您仅清除已开始的几个间隔中的 1 个。

编辑:如果不清楚,您可以在

gettimer
中每秒创建一个新的侦听器,因此页面加载的每一秒,您都将创建间隔。

不要创建多个监听器。它们不会仅仅因为您添加另一个事件或它们处理单个事件而自行删除或停止监听。


0
投票

您的错误是您尝试在设置间隔之前清除它。请参阅下面的代码片段,其中我首先进行相同类型的尝试,以便向您展示我为间隔创建的

int
变量在定义之前并不存在,因此,在 try-catch 块中正在尝试
clearInterval(int)
,但失败了,因为
int
尚不存在。

接下来,我设置一个间隔并将其 id 存储到名为

int
的变量中。本质上它每秒都会运行一个函数。

但是该函数会递增数字输入值,直到达到 10,然后清除

int
间隔,此时成功,因为它已正确初始化。

作为用户,您将在控制台中看到一条错误消息,并且计数器每秒增加一个值,直到达到 10。

try {
    clearInterval(int);
} catch (err) {
    console.log("clearing the interval errored out");
}
let int = setInterval(function() {
    if (++document.getElementById("foo").value === 10) clearInterval(int);
}, 1000);
<input type="number" id="foo" value="1">

© www.soinside.com 2019 - 2024. All rights reserved.