2017-02-09 13 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は 'interface'はJavaScriptの予約語ですhttps://mathiasbynens.be/notes/reserved-keywords#ecmascript-2 –

+0

変数tは私のjsで定義されています、私はそれを私の質問で数字に変更します – Adry

答えて

2

あなたのクロックIDが2回目の呼び出しで失われ、貧しいソリューションは

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

私は答えでより良い解決策を追加しました –

関連する問題