How Can I make setInterval countUp timer keep counting even in "Another Page" or "browser refresh"?

Viewed 426

i try to create some "visitor CountUp timer" on my header webpage. However when I select another tab, the timer is restart again from 00:00:00. Is there any solution to make it keep counting even in "Another Page" or "browser refresh"? I am not sure how to add sessionStorage into my current code.

Anyone willing to lend a hand on this?

Thanks

var sec = 0;
    function pad ( val ) { return val > 9 ? val : "0" + val; }
    setInterval( function(){
        document.getElementById("seconds").innerHTML=pad(++sec%60);
        document.getElementById("minutes").innerHTML=pad(parseInt(sec/60%60,10));
        document.getElementById("hours").innerHTML=pad(parseInt(sec/3600%60,10));
    }, 1000);
<span id="hours">00</span>:<span id="minutes">00</span>:<span id="seconds">00</span>

3 Answers

Your solution is using localstorage:

      var sec = 0;
      tmpSec = localStorage.getItem('secs')
      if (tmpSec != null) {
        sec = parseInt(tmpSec,10);
      }
      function pad ( val ) { return val > 9 ? val : "0" + val; }
      setInterval( function(){
        ++sec
        localStorage.setItem('secs', sec)
        document.getElementById("seconds").innerHTML=pad(sec%60);
        document.getElementById("minutes").innerHTML=pad(parseInt(sec/60%60,10));
        document.getElementById("hours").innerHTML=pad(parseInt(sec/3600%60,10));
      }, 1000);

Here is an example of interval which saved in localStorage https://github.com/syronz/micro-games/blob/master/02%20idle%20game/progress.html

var sec = 0;

that is going to reset your timer each time it is run.

But instead code it this way:

sessionStorage.sec = "0"; // only execute this when you want to reset your counter.

setInterval( function(){
  var sec = parseInt(sessionStorage.sec); 
  sec++;
  sessionStorage.sec = sec.toString();
  document.getElementById("seconds").innerHTML=pad(sec%60);
  document.getElementById("minutes").innerHTML=pad(parseInt(sec/60%60,10));
  document.getElementById("hours").innerHTML=pad(parseInt(sec/3600%60,10));
}, 1000);

You could add a query to the URL and then redirect to another URL with this query:

window.location.href += "?end=someTime"

Then you could set the timer to have this as the end:

var url = new URL(window.location.href);
var end = url.searchParams.get("end");
doSomething(end);
Related