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