2013-11-15 35 views
0

代碼看起來像這樣:重置的setInterval在JS

function startTimer(counter) { 
    var interval = setInterval(function() { 
     counter--; 
     $('#timer').html(counter); 
     // Display 'counter' wherever you want to display it. 
     if (counter == 0) { 
      clearInterval(interval); 
      $('#question').html("Time ended"); 
      setTimeout(function() { 
       window.location.href = "/"; 
      }, 5000); 
      return false; 
     } 
    }, 1000); 
} 

我想要做的是,當我多次調用該函數,每次都定時器復位到30秒,殺死所有過去的事例。目前,當我多次打電話時,它會因過去的實際情況而變得混亂起來。我究竟做錯了什麼?

+0

@naomik對不起,什麼? – heron

+0

請參閱此鏈接: http://stackoverflow.com/questions/8126466/javascript-reset-setinterval-back-to-0 – archu

回答

0

你必須定義功能外VAR間隔:

var interval; 
    function startTimer(counter) { 
     interval = setInterval(function() { 
      counter--; 
      $('#timer').html(counter); 
      // Display 'counter' wherever you want to display it. 
      if (counter == 0) { 
       clearInterval(interval); 
       $('#question').html("Time ended"); 
       setTimeout(function() { 
        window.location.href = "/"; 
       }, 5000); 
       return false; 
      } 
     }, 1000); 
    }