gpt4 book ai didi

javascript - 为什么我不能在下面的示例中使用 clearInterval?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:18 25 4
gpt4 key购买 nike

我有以下问题。当 timer_mou 开始计数时,当 pause 等于 closeit 时,它不会清除间隔。

我在这里错过了什么?

function my_timer(pause){
console.log('function: '+pause);

var timer_mou = setInterval(function() {
console.log('counting');
}, 5000);

if (pause == 'closeit') {
clearInterval(timer_mou);
}
}

最佳答案

只需将 setInterval 放在暂停函数之外,在全局范围内定义变量 timer_mou,然后当您调用您的函数时,它会正确清除它,而不是在每次函数调用时定义它,检查下面的工作示例。

希望这对您有所帮助。

var i = 0;
var timer;

start();

$('#pause').on('click',function(){
pause()
})

$('#restart').on('click',function(){
restart()
})

function pause(){
clearInterval(timer);
}

function restart(){
i=0;
pause()
start();
}

function start(){
timer = setInterval(function() {
i++;
console.log('Counting '+i);
},1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='pause'>Pause</button>
<button id='restart'>Restart</button>

关于javascript - 为什么我不能在下面的示例中使用 clearInterval?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41350392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com