2017-02-09 57 views
0

我有一個功能,顯示一個倒計時時鐘根據一個變量。在指定的條件下停止它的正確方法是什麼? clearTimeout不會停止遞減函數。停止的JavaScript倒計時功能,如果條件

function interface_vip(type){ 
    var timeout = ''; 
    var clock = ''; 
    //display clock 
    function Decrement() { 
     currentMinutes = Math.floor(secs/60); 
     currentSeconds = secs % 60; 
     if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds; 
      secs--; 
      if(secs !== -1) timeout = setTimeout(Decrement,1000); 
    } 
    if (type == 1){ 
     var mins = 20; 
     var secs = mins * 60; 
     var currentSeconds = 0; 
     var currentMinutes = 0; 
     clock = setTimeout(Decrement,1000); 
    } 
    if (type == 2){ 
     clearTimeout(clock); 
     clearTimeout(timeout); 
    } 
} 
+0

你有錯誤,t沒有定義 –

+1

l ook that'interface'是JavaScript中的一個保留字https://mathiasbynens.be/notes/reserved-keywords#ecmascript-2 –

+0

變量t在我的js中定義,我將其更改爲我的問題中的一個數字,它是工作 – Adry

回答

2

你的時鐘ID是在第二個電話丟了,一個貧窮的解決方案是創建全球

var timeout = ''; 
     var clock = ''; 
    function interface_vip(type){ 
     //display clock 
     function Decrement() { 
      currentMinutes = Math.floor(secs/60); 
      currentSeconds = secs % 60; 
      if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds; 
       secs--; 
       if(secs !== -1) timeout = setTimeout(Decrement,1000); 
     } 
     if (type == 1){ 
      var mins = 20; 
      var secs = mins * 60; 
      var currentSeconds = 0; 
      var currentMinutes = 0; 
      clock = setTimeout(Decrement,1000); 
     } 
     if (type == 2){ 
      clearTimeout(clock); 
      clearTimeout(timeout); 
     } 
    } 

在波紋管段

function interface_vip(){ 
 
    var timeout = ''; 
 
    var t = 0; 
 
    var clock = ''; 
 
    //display clock 
 
    function Decrement() { 
 
     currentMinutes = Math.floor(secs/60); 
 
     currentSeconds = secs % 60; 
 
     if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds; 
 
      secs--; 
 
      if(secs !== -1) timeout = setTimeout(Decrement,1000); 
 
    } 
 
    this.start = function(){ 
 
     var mins = t; 
 
     var secs = mins * 60; 
 
     var currentSeconds = 0; 
 
     var currentMinutes = 0; 
 
     clock = setTimeout(Decrement,1000); 
 
    } 
 
    this.stop = function(){ 
 
     clearTimeout(clock); 
 
     clearTimeout(timeout); 
 
    } 
 
} 
 
var interf = new interface_vip(); 
 
interf.start(); 
 
interf.stop();

一個更好的辦法變量
+0

謝謝!我看不到它。解決了問題:D – Adry

+0

我在答案中添加了更好的解決方案 –