Flipclock js倒计时1小时不复位

Flipclock js countdown 1hour without reset

本文关键字:复位 1小时 倒计时 js Flipclock      更新时间:2023-09-26

我正在尝试在不重置刷新时间的情况下进行倒计时。我需要倒计时1小时,但我不希望它在刷新时重置。从服务器获取当前时间和过期时间是不工作的,因为我想在点击上重置计时器。以下是我当前的js代码:

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

是的,你可以在你的例子中使用flipclockjquery-cookie看看1分钟倒计时示例

flipclock在cookie中存储End Date的init()功能中,用clock.setTime()初始化定时器,用clock.setCountdown(true)使能倒计时,用clock.start()启动倒计时。

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

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

点击reset按钮将通过移除cookie 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