2

I'm trying to make a countdown without resetting the time on refresh. I need to countdown 1h only but I don't want it to reset on refresh. Getting the current time from server and expiration time is not working since I want to reset that timer on a click. Here is my current js code:

<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>
4

1 回答 1

3

是的,您可以在示例中使用Flipclockjquery-cookie来执行此操作,请查看1 分钟倒计时示例

在将结束日期存储在 cookie 中的init()功能中,使用 初始化计时器,使用 启用倒计时并通过 启动它。flipclockclock.setTime()clock.setCountdown(true)clock.start()

现在如果用户刷新页面,我们设置了当前日期和结束日期之间的计时器,所以像这个计数器可以正常继续倒计时:

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

单击reset按钮将通过删除 cookieendDate并初始化倒计时功能来重置计数器。

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
于 2015-07-28T11:54:58.037 回答