我有一个倒计时功能。该函数使用 setTimeout()
重复调用自身:
function countDownSendCode(timer) {
if(timer >= 0) {
document.querySelector('#send-code').setAttribute('disabled', true);
document.querySelector('#send-code').innerHTML = timer + 's later resend';
setTimeout(function() {
countDownSendCode(timer - 1);
}, 1000);
} else {
document.querySelector('#send-code').removeAttribute('disabled');
document.querySelector('#send-code').innerHTML = 'Send';
}
}
document.querySelector('#send-code')
是一个用于发送代码的按钮。当用户点击该按钮时,在倒计时结束之前他不能再次点击它。
我在按钮的 click
事件中添加了以下函数来调用倒计时:
function clickSendCode(ev) {
ev.preventDefault();
countDownSendCode(5); // call the count down here
handleAjaxRequest();
}
在某些情况下,在 handleAjaxRequest()
中,我需要停止倒计时并立即使按钮可用。
我可以调用 countDownSendCode(-1)
来设置可用的按钮,但是如何清除 setTimeout()
?因为是自己调用的,所以无法得到clearTimeout()
需要的timeID。
最佳答案
您可以实现此功能,如以下代码片段所示:
// global var serving as a handle to Timer
var _timer;
// call this function to start timer
function StartMyTimer()
{
_timer = setTimeout(function(){ alert("Hello, Timer is Running!"); }, 5000);
}
// call this function to stop timer
function StopMyTimer()
{
clearTimeout(_timer);
}
我还建议您考虑一对函数:setInterval()
和 clearInterval()
,它们可以简化重复任务的编码。
希望这会有所帮助。
关于javascript - 如何停止一个自调用的 setTimeout() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35809819/