2015-07-28 101 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