简体   繁体   English

如何防止我的JavaScript计时器重新启动页面重新加载

[英]How to keep my javascript timer from restarting on page reload

I have this code in my PHP include file for an online quiz. 我的PHP包含文件中包含此代码,用于在线测验。 How do I stop my javascript timer from restarting on page refresh? 如何停止我的JavaScript计时器重新启动页面刷新? I am new to local storage and cookies. 我是本地存储和Cookie的新手。 Please I will need someone to help with an example code or modify my code. 请我帮别人提供示例代码或修改我的代码。

<div class="timer">Time Remaining <span id="display"></span> minutes!</div> 

<script>
    function CountDown(duration, display) {
        if (!isNaN(duration)) {
            var timer = duration, minutes, seconds;

            var interVal=  setInterval(function () {
                minutes = parseInt(timer / 60, 10);
                seconds = parseInt(timer % 60, 10);

                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;

                $(display).html("<b>" + minutes + "m : " + seconds + "s" + "</b>");

                if (--timer < 0) {
                   timer = duration;
                   SubmitFunction();
                   $('#display').empty();
                   clearInterval(interVal)
                }
            },1000);
        }
    }

    function SubmitFunction(){
        window.location.href = "quizResult.php";    
    }

    CountDown(60,$('#display'));    

</script>

Like @geekley stated, you can store the time when the timer began initially. 就像@geekley所说的那样,您可以存储计时器最初开始的时间。 An easy way to do this is to leverage localstorage, which you've mentioned not knowing a lot lot about yet. 一种简单的方法是利用本地存储,您已经提到了它还不了解很多。

What I might do, is set the time initally like this: 我可能会做的就是这样设置时间:

localStorage.setItem('StartTime', Date.now())

When a user visits, or loads the page, you can have an initial check for this value. 当用户访问或加载页面时,您可以对此值进行初步检查。 So this line of code might change to: 因此,这行代码可能会更改为:

var startTime = localStorage.getItem('StartTime')

// if startTime exists, calculate your counter like so:
// timeRemaining = (initial countdown value) - (CurrentTime - StartTime)

var timeRemaining // declare this variable and set it to whatever value you'd like as a default

if (startTime) {
    timeRemaining = timeRemaining - (Date.now() - startTime)
} else {
    localStorage.setItem('StartTime', Date.now())
}

Then, call your CountDown function passing timeRemaining variable as the argument. 然后,调用CountDown函数,将timeRemaining变量作为参数传递。 You'll probably have to edit your logic to calculate milliseconds to minutes, but it looks like you have a good grasp on that. 您可能需要编辑逻辑以计算毫秒到分钟,但是您似乎对此很有把握。 I hope this helps! 我希望这有帮助!

EDIT 编辑
Comparing instances of Date.now() will return milliseconds. 比较Date.now()的实例将返回毫秒。 You could check the mozilla docs for more info about dealing with this. 您可以查看mozilla文档以获取有关处理此问题的更多信息。

Your code is showing nothing . 您的代码什么也没显示。 Anyway , you can use the code below where you need to set the end time of the quiz which will give you the exact timer whether or not you refresh the page . 无论如何,您可以使用下面的代码来设置测验的结束时间,无论您是否刷新页面,它都将为您提供确切的计时器。

<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
  text-align: center;
  font-size: 60px;
  margin-top:0px;
}
</style>
</head>
<body>

<p id="demo"></p>

<script>

    var countDownDate = new Date("Jul 7, 2018 00:06:25").getTime();

    var x = setInterval(function(){

        var now = new Date().getTime();

        var distance = countDownDate - now;

        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));

        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        document.getElementById("demo").innerHTML = minutes + "m " + seconds + "s ";

        if (distance < 0) {
            clearInterval(x);
            document.getElementById("demo").innerHTML = "EXPIRED";
        }

    }, 1000);

</script>

</body>

</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM