如何停止一个自调用的setTimeout()函数?

3

我有一个倒计时函数。该函数使用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。

为什么不能使用一个变量来保存 timeoutID - Rayon
3个回答

3
您可以通过以下代码片段实现此功能:
// 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(),它们可以简化重复任务的编码。
希望这会有所帮助。

1
一个全局变量。非常简单。谢谢! - Brick Yang
欢迎您。如果您对解决方案感到满意,请标记答案为已接受。祝您的项目好运。最好的问候, - Alexander Bell

0
function countDownSendCode(timer) { 
    if(timer >= 0) {
        document.querySelector('#send-code').setAttribute('disabled', true);
        document.querySelector('#send-code').innerHTML = timer + 's later resend';
       countDownSendCode._timer = setTimeout(function() {
            countDownSendCode(timer - 1);
        }, 1000);
    } 
    else {
        if('stop'===timer){
            clearTimeout(countDownSendCode._timer);     
        }
        document.querySelector('#send-code').removeAttribute('disabled');
        document.querySelector('#send-code').innerHTML = 'Send';
    }
}

修改countDownSendCode函数如上所述。当您需要立即使按钮可用时,请使用'stop'字符串调用它。


0
我建议不要递归调用countDownSendCode()函数。相反,最好一开始就将计时器设置为正确的秒数,然后您可以返回计时器的引用并将其传递给ajax处理程序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接