[英]Why Does clearInterval only works the first time?
这是我的代码如下:
function triggerTimer() {
var myInt = window.setInterval(timerStart, 1000);
setTimeout(removeInt, 4000);
}
function timerStart() {
var timerValue = parseInt(document.getElementById('timer').innerHTML);
if (timerValue > 0) {
timerValue -= 1;
document.getElementById('timer').innerHTML = '0' +timerValue.toString();
console.log(timerValue);
}
else {
var correct = document.getElementById(`c${row}`).innerHTML;
multiplechoice.innerHTML = '<p>The correct answer is <span style="color: white;" id=`c${row}`>'+correct+'</span><br><button onclick="submitEntry();">Next Question</button></p>';
}
}
function removeInt() {
if(clearInterval(myInt)) {console.log('success')} else {console.log('fail')}
}
这段代码上面是一个计时器,每次调用 timerStart function 时它都会递减。 问题是计时器在第一次触发 removeInt function 时停止,即使它记录“失败”。
但是第二次触发timerStart,时间还是减少了,但是调用removeInt的时候,interval并没有被清除。
您正在记录failed
,因为 clearInterval 即使成功也会返回 undefined 。
所以你的removeInt
function,
if(clearInterval(myInt)) {console.log('success')} else {console.log('fail')}
得到这样的评价,
if(undefined) {console.log('success')} else {console.log('fail')}
这是有关clearInterval
的文档以获取更多信息, https://developer.mozilla.org/en-US/docs/Web/API/clearInterval
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.