我有倒計時功能。該函數用於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。
你不能使用變量來保存'timeoutID'嗎?全局變量爲 – Rayon