简体   繁体   中英

How do i avoid reset the timer value on Page Refresh / Page Loading using java script?

here is my code in which i have use readCookies function but when it's not responding, it shows nothing in the div even alert is also not working.

seconds = readCookie('countdown') || 60;
alert(seconds);

function secondPassed() {
    seconds--;
    var minutes = parseInt(seconds / 60);
    var remainingSeconds = parseInt(seconds % 60);
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + parseInt(remainingSeconds);
    }
    document.getElementById('countdown').innerHTML = minutes + " mins : " + remainingSeconds + " secs";
    if (parseInt(seconds) === 0) {
        alert("Time is over");
        clearInterval(countdownTimer);
        document.getElementById('countdown').innerHTML = "Time is Over";
        document.forms["myForm"].submit();
        document.location.href = "examresult.jsp";
    }
}
var countdownTimer = setInterval(function () {
    secondPassed();
    if (seconds === 0) {
        eraseCookie(seconds);
    } else {
        createCookie(seconds, seconds, 7);
    }
}, 1000);

Store the value in a cookie or browser storage, before page unload and re-load it from cookie or browser storage in page refresh.

For example (pseudo-code):

window.onunload = function(){
     set_cookie('timer', timer) /* you need to implement this function */;
}

window.onload = function() {
   timer = get_cookie('timer'); /* you need to implement this function */
   if ( null == timer ) timer = 0; /* not page refresh, start a new timer */
}

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