2016-04-09 9 views
0

//このタイマーは、1分に達した後に2:00にリセットされたままになります。また、私は適切な時にタイムアップを言う通知を取得しません。誰かがコードを修正してください。また、タイマーの停止/再開ボタンも機能し続ける必要があります。JavaScriptタイマーのリセットが遅すぎる(動作しない)

var isRunning = false; 
 
var ticker; //this will hold our setTimeout 
 
var seconds, 
 
    minutes; 
 

 
function countdown(mins, secs) { 
 
    //i made these global, so we can restart the timer later 
 
    seconds = secs || 60; //if user put in a number of minutes, use that. Otherwise, use 60 
 
    minutes = mins; 
 
\t console.log('time stuff',mins,secs,minutes,seconds) 
 
    function tick() { 
 
    var counter = document.getElementById("timer"); 
 
    var current_minutes = mins - 1 
 
    seconds--; 
 
    counter.innerHTML = 
 
     current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds); 
 
    if (seconds < 1 && minutes) { 
 
\t \t \t //seconds reached 0, and still minutes left; 
 
     seconds=60; 
 
     minutes--; 
 
    } 
 
    if ((seconds > 0 || minutes > 0) && isRunning) { 
 
     ticker = setTimeout(tick, 1000); 
 
    } else if(isRunning){ 
 
    \t console.log(seconds,minutes,isRunning) 
 
     alert('Time\'s up, brah!') 
 
    } 
 
    } 
 
    tick(); 
 
} 
 

 
function timeToggle() { 
 
\t isRunning = !isRunning; //if it's false, set it true. If it's true, set it false. 
 
    if (!isRunning) { 
 
    clearTimeout(ticker); //or whatever else you set the initial timeOut to. 
 
    } else { 
 
    //not running! and time is defined; 
 
    var sec = seconds||60; 
 
    console.log('def!',minutes, sec) 
 
    countdown(minutes, sec); 
 
    
 
    } 
 
    
 
} 
 
isRunning = true; 
 
countdown(2);
<div id="timer">2:00</div> 
 
<button onclick="timeToggle()">Stop time</button>

答えて

0

あなたのロジックに小さな問題が存在します。カウントダウンの初期化、あなたは、あなたが秒を初期化していない場合は効果的にあなたが望む時間に60秒を追加

seconds = secs || 60; 

を行う時には

。参照:

function countdownInit(mins, secs) { 
    seconds = secs || 60; 
    minutes = mins; 
    console.log(mins + 'min ' + seconds + 'sec'); 
} 

countdownInit(1, 30) // ok 
// 1min 30sec 

countdownInit(1) // not ok 
// 1min 60sec 
// thats 2 minutes 

ここで第二の問題は、あなたが時間を表示するminutes - 1に等しいVAR current_minutesを使用することです。あなたは本当のカウンターを見せていません。

修正は以下の通りです:

function countdown(mins, secs) { 
    seconds = secs; 
    minutes = mins; 
    // if secs is 0 or uninitialized we set seconds to 60 and decrement the minutes 
    if(!secs) { 
     minutes--; 
     seconds = 60; 
    } 

    function tick() { 
     var counter = document.getElementById("timer"); 
     seconds--; 
     // we use minutes instead of current_minutes in order to show what's really in our variables 
     counter.innerHTML = 
      minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds); 

     // rest of code 
    } 
    // rest of code 
} 

私は可能な限りあなたのコードな限り維持しようとしました。

関連する問題