2016-03-05 39 views
2

我有倒計時功能。該函數用於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。

+0

你不能使用變量來保存'timeoutID'嗎?全局變量爲 – Rayon

回答

1

可以實現這個功能顯示在下面的代碼片段:

// 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

。這很簡單。謝謝! –

+0

不客氣。如果您對解決方案感到滿意,請標記接受的答案。祝你的項目好運。最好的祝福, –

0

我建議不遞歸調用countDownSendCode()。相反,只需將計時器設置爲正確的秒數即可,然後您可以將計時器返回給計時器並將其傳遞給ajax處理程序。

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'來調用它。