2015-03-25 50 views
0

我想要一個簡單的倒計時,一個倒計時,當時間完成時自動開始,倒計時開始,當我點擊按鈕。如何進行自動倒計時,繼續點擊下一步點擊查看原圖(大圖)javascript

我一直在試圖解決這個問題,我做了下面的代碼,我不能做這兩個選項,我設法做到以下代碼:當倒計時完成後,它再次統計,請參閱片段

我更不知道如何做到這一點,這裏是我的代碼:

JS

var i = 1; 

function Countdown(options) { 
    var timer, 
     instance = this, 
     seconds = options.seconds || 10, 
     updateStatus = options.onUpdateStatus || function() {}, 
     counterEnd = options.onCounterEnd || function() {}; 

    function decrementCounter() { 
     updateStatus(seconds); 
     if (seconds === 0) { 
      instance.stop(); 
      counterEnd(); 
      return; 
     } 
     seconds--; 
    } 

    this.start = function() { 
     timer = 0; 
     seconds = options.seconds; 
     timer = setInterval(decrementCounter, 1000); 
    }; 

    this.stop = function() { 
     clearInterval(timer); 
    }; 
} 

var myCounter = new Countdown({ 
    seconds:5, // number of seconds to count down 
    onUpdateStatus: function(sec){$('#countdown').html(sec);}, // callback for each second 
    onCounterEnd: function(){  
     myCounter.start(); 
    } // final action 
}); 

myCounter.start(); 

$("#button").click(function() { 
    myCounter.start(); 
}); 

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<p id="countdown"></p> 
<button type="button" id="button">restart</button> 

你有什麼想法如何解決?

感謝

+0

我真的不明白有什麼問題嗎?什麼應該解決? – OddDev 2015-03-25 12:13:34

+0

只需嘗試一下我的代碼,就會發現當我們點擊按鈕重新開始倒計時時,它不能正常工作 – 2015-03-25 12:18:40

+0

您的點擊事件在文檔準備就緒之前就已啓動,您需要將其包裝在$(document ).ready(function(){});在我的答案中看看plunker演示。 – KungWaz 2015-03-25 13:23:48

回答

1

試試這個,你必須有一個$(document).ready函數。

var i = 1; 

function Countdown(options) { 
    var timer, 
     instance = this, 
     seconds = options.seconds || 10, 
     updateStatus = options.onUpdateStatus || function() {}, 
     counterEnd = options.onCounterEnd || function() {}; 

    function decrementCounter() { 
     updateStatus(seconds); 
     if (seconds === 0) { 
      instance.stop(); 
      counterEnd(); 
      return; 
     } 
     seconds--; 
    } 

    this.restart = function() { 
     seconds = options.seconds; 
    } 

    this.start = function() { 
     seconds = options.seconds; 
     timer = setInterval(decrementCounter, 1000); 
    }; 

    this.stop = function() { 
     clearInterval(timer); 
    }; 
} 

$(document).ready(function() { 
    var myCounter = new Countdown({ 
     seconds:5, // number of seconds to count down 
     onUpdateStatus: function(sec){ 
      $('#countdown').html(sec); 
     }, // callback for each second 
     onCounterEnd: function(){  
      myCounter.start(); 
     } // final action 
    }); 

    myCounter.start(); 

    $("#button").on('click', function() { 
     myCounter.restart(); 
    }); 
}); 

Plunker demo