简体   繁体   中英

How to stop resetting a JavaScript timer while refreshing the page

I am doing an online examination page. In this page I have a countdown timer that counts down by a value from the database. It's working fine but when I refresh the page it resets. I have to stop the timer from resetting.

Here is my JavaScript timer code:

<script type="text/javascript">
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>" +"Time Remaining: "+ minutes + "m : " + seconds + "s" + "</b>");
            if (--timer < 0) {
                timer = duration;
                SubmitFunction();
                $('#display').empty();
                clearInterval(interVal)
            }
        },1000);
    }
}

function SubmitFunction(){
    $('#result').click();
}

CountDown(<?php echo $t*30; ?>,$('#display')); //$t comes from database

function disable_f5(e) {
    if ((e.which || e.keyCode) == 116) {
        e.preventDefault();
    }
}

$(document).ready(function(){
    $(document).bind("keydown", disable_f5);
});
</script>

I just saw your question and am going to take a crack at it. One thing that I recommend is trying to commit the values to local storage. You could add an event listener, have it specify to listen for a reload, and on that reload commit the integer value to local storage in JSON format. Just an idea.

If you are using a db already, what about adding a table or an extra field to an existing table that registers the datetime that the user commenced the examination and then on each page load - you can get the commencement time from the db, do some funky calculations and then display the remaining time.

That way you are not relying on the calculation in browser keeping track (although I would probably try session storage for it as already suggested), but a constant start time that you can confidently calculate from.

try this as an approach - note only skeleton of code listed to demonstrate approach. I would personally set the datetime in the db though.

//at commencement of exam
//js var commencementTime = (//calculation to get current time);

localStorage.setItem('commencementTime ',commencementTime );

//on page reload
var commencementTime= localStorage.getItem('commencementTime ');
    if(commencementTime){ 
    //code for calculating countdown}

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