在Javascript中多次刷新后保持计时器一致 [英] Keeping a timer consistent after multiple refreshes in Javascript

查看:93
本文介绍了在Javascript中多次刷新后保持计时器一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个倒数计时器,当我快速按f5时,计时器冻结。
我猜这是因为页面在setInterval之前重新加载。
我正在寻找一种重新加载页面的方法,同时保持计时器运行发生的事情是在setInterval甚至完成之前页面重新加载

I have a countdown timer and when ever I rapidly press f5 the timer freezes. im guessing this is because the page reloads before the setInterval. i'm looking for a way to reload the page and at the same time keep the timer running whats happening is the page reloads before the setInterval could even finish

<h3 style="color:#000000" align="center">
         Time Remaining : <span id='timer'></span>
         </h3>

<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script>

//define your time in second
    var c = localStorage.getItem("timer");
    if(c == null)c = 3600;

    var t;
    timedCount();

    function timedCount()
    {

        var hours = parseInt( c / 3600 ) % 24;
        var minutes = parseInt( c / 60 ) % 60;
        var seconds = c % 60;

        var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes <        10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);


        $('#timer').html(result);
        if(c == 0 )
        {
            //setConfirmUnload(false);
            //$("#quiz_form").submit();
            window.location="logout.html";
        }
        c = c - 1;
        localStorage.setItem("timer", c);
        t = setTimeout(function()
        {
            timedCount()
        },1000);


    }


</script>


推荐答案

存储计时器应该在计时器完成的时间开始,然后从该值中减去当前时间,得到计时器结束的时间。 日期对象适用于此。

Store the time that the timer should finish when the timer starts, then just subtract the current time from that value to get the time until the timer should finish. The Date object works well for this.

HTML

<p id="display">Time Left<p>
<button id="start">Start</button>

Javascript

Javascript

var start = document.getElementById("start");
var dis = document.getElementById("display");
var finishTime;
var timerLength = 10;
var timeoutID;
dis.innerHTML = "Time Left: " + timerLength;

if(localStorage.getItem('myTime')){
    Update();
}
start.onclick = function () {
    localStorage.setItem('myTime', ((new Date()).getTime() + timerLength * 1000));
    if (timeoutID != undefined) window.clearTimeout(timeoutID);
    Update();
}

function Update() {
    finishTime = localStorage.getItem('myTime');
    var timeLeft = (finishTime - new Date());
    dis.innerHTML = "Time Left: " + Math.max(timeLeft/1000,0);
    timeoutID = window.setTimeout(Update, 100);
}

请参阅此处的工作示例: JSFiddle

See working example here: JSFiddle

这篇关于在Javascript中多次刷新后保持计时器一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆