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

标签 javascript settimeout

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

相关文章:

javascript - 如何在指令 Controller 中注入(inject)依赖项

javascript - jslint:为什么此代码会导致 "Strict violation"错误消息?

javascript - 理解一个接一个地执行 setTimeout() 函数

javascript - 如何添加时间函数来单击

javascript - 每 500 毫秒 http 请求一次,直到请求完成 Angular

javascript - 是什么让 ReactJS 像它声称的那样快?

javascript - 如何根据另一个值 [JavaScript] 在对象数组中搜索特定值?

javascript - v-model 并选择多个

javascript - 使用 TypeScript 的延迟 javascript/jQuery 搜索不等待

javascript - setTimeout 和重新加载 iframe 的问题