2015-06-22 54 views
0

我在我的網站上有一個測驗,如果時間到了,它會提交。表單提交後(通過jQuery),我想定時器停止工作。測試提交後,我嘗試了return: false,但這並不奏效。從2個Javascript循環中退出(或停止腳本)

HTML:

<span id="time">30:00</span> 

的javascript:

var thirtyMinutes = 60 * 30, 
    display = document.querySelector('#time'); 
startTimer(thirtyMinutes, display); 

function startTimer(duration, display) { 
var timer = duration, minutes, seconds; 
setInterval(function() { 
    minutes = parseInt(timer/60, 10) 
    seconds = parseInt(timer % 60, 10); 

    minutes = minutes < 10 ? "0" + minutes : minutes; 
    seconds = seconds < 10 ? "0" + seconds : seconds; 

    display.textContent = minutes + ":" + seconds; 

     if ($('#time').html() == '00:00'){ 
      alert("There is no time left remaining. The test will now submit."); 
      $('#submitTest').trigger("click"); //submit the test 

      //this is where I would like to exit the script and stop the timer from working 
     } 

    if (--timer < 0) { 
     timer = duration; 
    } 

}, 1000); 

} 
+0

'setTimeout'而不是'setInterval'? – PSkocik

回答

0

要停止setInterval的,你必須使用這個

clearInterval(n); 

並把

var n = setInterval(function() {....