Skip to content
Advertisement

Javascrip count down timer: prevent reseting on page reload

I have a minute timer which counts from 15 to 0. I don’t want to reset (= restart) the timer on page reload. but I can’t figure out how to prevent the timer from resetting on a page reload. I’m using javascript with php. I have tried to add the timer time on load to php session but that didn’t work for me. any suggestions? thank you 🙂

function startTimer() {
    setTimeout('timer()', 60);
}

  var continueMins = localStorage.getItem("continueMins");
  var continueSecs = localStorage.getItem("continueSecs");
  
  if (continueMins == 'true') {
    mins = continueMins;
  } else {
    mins = 15;
  }

  if (continueSecs == 'true') {
    secs = continueSecs;
  } else {
    secs = mins * 60;
  }

  function timer() {
    if (document.getElementById) {
        minutes = document.getElementById("minutes");
        seconds = document.getElementById("seconds");
        progressBar = document.getElementById("progressBar");
        timerContainer = document.getElementById("timer-container");
        expired = document.getElementById("expired");
        btcAmount = document.getElementById("btcAmount");
        btcAddress = document.getElementById("btcAddress");

        window.onbeforeunload = function() {
            localStorage.setItem("continueMins", getMinutes());
            localStorage.setItem("continueSecs", getSeconds());
        }

        var totalSeconds = 15 * 60, remainingSeconds = getMinutes() * 60 + getSeconds();

        progressBar.style.width = (remainingSeconds * 100 / totalSeconds) + "%";

        minutes.innerHTML = getMinutes() < 10 ? "0" + getMinutes() : getMinutes();
        seconds.innerHTML = getSeconds() < 10 ? "0" + getSeconds() : getSeconds();

        if (mins < 1) { 
            minutes.classList.add("text-danger");
            seconds.classList.add("text-danger");
        }

        if (mins < 0) {
            expired.style.display = 'block';
            timerContainer.style.display = 'none';
            btcAmount.text = 'Expired';
            btcAddress.text = 'Payment Window Expired';
            localStorage.removeItem("continueMins");
            localStorage.removeItem("continueSecs");
        } else {
            secs--;
            setTimeout('timer()', 1000);
        }

    }
}

function getMinutes() {
    mins = Math.floor(secs / 60);
    return mins;
}

function getSeconds() {
    return secs - Math.round(mins * 60);
}

startTimer();
<p class="font-18 font-500"><span id="minutes"></span> : <span id="seconds"></span></p>

Advertisement

Answer

You could use the localStorage (sessionStorage is also an option but more prone to restart your timer if the user e.g. reconnects in a new tab or restarts the browser)
How to do it to be on the save side (crashes, unexpected bahaviour e.g.you should update the elapsed time in your local storage from time to time. The “normal” situations are handled by checking for the respective event:

var aTimer, bool;
window.onbeforeunload = function (e) {
    if (bool) return;
    aTimer = setTimeout(function () {
       bool = true;
    localStorage.setItem("resetTimer", "false");      
    localStorage.setItem("currentTimer", MY_TIMER_VAR);
    localStorage.setItem("sessionDate", MY_NEW_SESSION_VAR);
 }, 500);
 return ; 
};

EDIT If you want that an elapsed timer is valid for lets say 24 hours you have also to place MY_NEW_SESSION_VAR which is a Date.now() converted in hours when reloading you check against TODAY_DATETIME_IN_HOURS which is a Date.now() converted in hours (This was my use case, if you do not need it just leave it out)

The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
When starting your program (loading js) you should check for the vars with:

 var resetTimer = localStorage.getItem("resetTimer");
 var sessionDate = localStorage.getItem("sessionDate");  
 if (resetTimer == "true" || sessionDate > (TODAY_DATETIME_IN_HOURS - 24) ){ // start timer }

To delete a single item

 localStorage.removeItem("sessionDate");

If you want to use sessionStorage just replace localStorage with sessionStorage
EDIT full code for the OP tested and working as asked

var countDownTarget;

if (document.readyState!="loading") docReady();
/* Modern browsers */
else document.addEventListener("DOMContentLoaded", docReady);
function docReady() {
  countDownTarget = parseInt(localStorage.getItem("countDownTarget"));
 console.debug("Initvalue: " + countDownTarget);
 if (isNaN(countDownTarget) == true || countDownTarget == "" || countDownTarget <= 0){  // If not defined
    countDownTarget = new Date().getTime() + 15 * 60 * 1000;
    console.debug("is NaN sInitvalue: " + countDownTarget);
  //Update the count down every 1 second
   setInterval(countDown, 1000);
    } else {
    console.debug("else Initvalue: " + countDownTarget);
    setInterval(countDown, 1000);
    }
}

window.onbeforeunload = function() {
    localStorage.setItem("countDownTarget", countDownTarget);
};

// Functions you call
function countDown(){
    var now = new Date().getTime();  
    //console.debug("now " + now);  
    var distance = countDownTarget - now;
    console.debug("distance " + distance);
    var mins = distance < 0 ? 0 : Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var secs = distance < 0 ? 0 : Math.floor((distance % (1000 * 60)) / 1000);        
/** Add a zero in front of numbers<10 */
    mins = prependZero(mins);
    secs = prependZero(secs);
 // Output the results
    document.getElementById("minutes").innerHTML = mins;
    document.getElementById("seconds").innerHTML = secs;

    if (distance <= 0) {
 //   clearInterval(x);
    localStorage.removeItem("countDownTarget");
    clearInterval(countDown); 
    }

}

function prependZero(i){
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

Copy between your script tags or load as *.js file

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement