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>
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