2015-07-28 103 views
1

我試圖在不重置刷新時間的情況下進行倒計時。我只需要倒計時1h,但我不希望它在刷新時重置。從服務器和過期時間獲取當前時間不起作用,因爲我想通過點擊重置該定時器。這是我目前的js代碼:Flipclock js倒計時1小時無重置

<script> 
    var clock; 


    clock = $('.clock').FlipClock({ 
     clockFace: 'HourlyCounter', 
     autoStart: false, 
     callbacks: { 
      stop: function() { 
       $('.message').html('The clock has stopped!') 
      }, 
     } 
    }); 
    clock.setTime(3600); 
    clock.setCountdown(true); 
</script> 

回答

2

是的,你可以做到這一點使用flipclockjquery-cookie看看1 minute countdown Example在你的榜樣基礎。

flipclockinit()函數存儲在cookie中的結束日期,初始化定時器clock.setTime(),使倒數與clock.setCountdown(true)和由clock.start()啓動它。

現在,如果用戶刷新頁面,我們設置了定時與當前的日期和結束日期之間的差別,所以像這樣的計數器可以繼續正常倒計時:

var counter = $.cookie('endDate')-currentDate; 
clock.setTime(counter); 

點擊reset按鈕將通過移除計數器復位餅乾endDate和初始化倒計時功能。

HTML:

<div class="clock" style="margin:2em;"></div> 
<div class="message"></div> 
<button id='reset'>Reset</button> 

JS:

//ready function 
$(function(){ 

    countDown = function(){ 
     var currentDate = Math.round(new Date()/1000); 

     var clock = $('.clock').FlipClock({ 
      countdown: true, 
      callbacks: { 
       init: function() { 
        //store end date If it's not yet in cookies 
        if(!$.cookie('endDate')){ 
         // end date = current date + 1 minutes 
         var endDate = Date.now() + 1*60*1000; 

         // store end date in cookies 
         $.cookie('endDate', Math.round(endDate/1000)); 
        } 
       }, 
       stop: function() { 
        $('.message').html('The clock has stopped!'); 
       }, 
      } 
     }); 

     /* counter will be at first 1 min if the user refresh the page the counter will 
      be the difference between current and end Date, so like this counter can 
      continue the countdown normally in case of refresh. */ 
     var counter = $.cookie('endDate')-currentDate; 

     clock.setTime(counter); 
     clock.setCountdown(true); 

     clock.start(); 
    } 

    //reset button 
    $('#reset').click(function(){ 
     $.removeCookie('endDate'); //removing end date from cookies 
     countDown(); //launch countdown function 
    }); 

    //Lanching count down on ready 
    countDown(); 
}); 

在你的情況(1小時),你只有在該行的1 60替換:

var endDate = Date.now() + 1*60*1000; // For you .... + 60*60*1000