简体   繁体   中英

How to keep my javascript timer from restarting on page reload

I have this code in my PHP include file for an online quiz. How do I stop my javascript timer from restarting on page refresh? I am new to local storage and cookies. 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. 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. 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. You could check the mozilla docs for more info about dealing with this.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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