2016-09-07 65 views
0

我使用moment.js創建了一個三分鐘的倒計時。但是,每當頁面加載時,計時器遞減1秒鐘並在2:59停止。打印變量如futuredifference似乎會產生正常的結果,但是,所以我相信我的錯誤在於倒計時。我的倒計時有什麼問題?Moment.js倒計時不會減少超過一秒

這裏是我的代碼:

<script type="text/javascript"> 
     $(document).ready(function(){ 
      var now = moment(); 
      var future = moment(now).add(3, 'm'); 
      var difference = future - now; 
      var duration = moment.duration(difference, 's'); 
      var interval = 1000; 

      setInterval(function() { 
       if(duration.asSeconds() <= 0) { 
        clearInterval(intervalId); 
        document.getElementById("clock").innerHTML = moment(duration.asSeconds()).format("m:s"); 
       } 

       duration = moment.duration(duration.asSeconds() - 1, 's'); 
       document.getElementById("clock").innerHTML = moment(duration.asSeconds()).format("m:s"); 
      }, interval); 
     }); 
    </script> 

回答

0

您可以更改到是這樣的:

if (moment.duration(future - moment()).asSeconds() <= 0) {

,改變

duration = moment.duration(duration.asSeconds() - 1, 's');

duration = moment.duration(moment.duration(future - moment()).asSeconds(), 's');

,因爲你是閉合捕捉duration值以上,但從來沒有真正更新它。

+0

使用duration.toString()打印出結果,我得到PT2M59S而不是3:00。但是,它似乎正在減少。 – Lyxpudox

+0

這是因爲持續時間符合ISO 8601 https://en.wikipedia.org/wiki/ISO_8601#Time_intervals如果您想要格式化的字符串,您可以使用'humanize()'http://momentjs.com/docs/# /持續時間/ –

+0

對不起,但'humanize()'創建了類似'3分鐘'的東西。我正在尋找一個可以倒計時的時鐘,每秒更新一次。 – Lyxpudox