Click here to Skip to main content
15,886,860 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
When I refresh the page the timer reset, I want it to continue to count even I refresh or restart the browser. But it will continue to count when I clicked the start button again. Please help.

Here's my code.

HTML code
HTML
<pre><!DOCTYPE html>
<html lang="en">
    <head>
        <title>Timer</title>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script></script>
    </head>
<body>
        <span id="countup">00:00:00</span>
        <button type="button" id="attendance_button">Start</button>
</body>
</html>

JS code
<pre lang="Javascript"><pre><script type="text/javascript">
    (function(){
$("#attendance_button").click( function(){

    getlocalStoragetime();
});
})()

function getlocalStoragetime()
{
    var time = localStorage.getItem('timer') || "00:00:00",
        parts = time.split(':'),
        hours = +parts[0],
        minutes = +parts[1],
        seconds = +parts[2],
        span = $('#countup');

    function correctNum(num) {
        return (num<10)? ("0"+num):num;
    }

    var timer = setInterval(function(){
        seconds++;
        if(seconds > 59) {
            minutes++;
            seconds = 0;

            if(minutes > 59) {
                hours++;
                seconds = 0;
                minutes = 0;

                if(hours >= 24) {
                  alert("You're logged-in for 24 hours.");
                }
            }
        }
        var displayTime = correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds);
        localStorage.setItem('timer', displayTime);
        span.text(displayTime);
    }, 1000); 
}
</script>


What I have tried:

i tried to put it into a function(timer code) and just call that function but it won't work.
Posted
Updated 23-May-22 2:10am

You need to learn how things work: when you refresh a page, your request a new copy of it from the server, and that discards everything that has been done to the page so far - and that includes timers. You can't start a timer that works even when the page it is running on has been discarded for any reason, unless you run the timer at the server instead of the client.

You could use a cookie to save the current timer value, and update that every time the timer ticks but that's a messy solution at best, and prone to "losing time" unless you are very careful how you do it.
 
Share this answer
 
<!DOCTYPE html>





<title>timer



body {
background: #202020;
color: white;
}
button {
width: 100px;
height: 30px;
border: 3px solid white;
border-radius: 50px;
background: #202020;
color: white;
cursor: pointer;
/*outline: none;*/
}
.font {
color: white;
}

#stopwatch {
font-size: 50px;
position: absolute;
top: 50%;
left: 50%;
/*left-right top-bottom*/
transform: translate(-50%, -60%);
}
#buttons {
position: absolute;
top: 50%;
left: 50%;
/*left-right top-bottom*/
transform: translate(-55%, -1%);
}
#buttons li {
display: inline;
padding-left: 10px;
}




00 : 00 : 00


  • Start
  • Stop
  • Reset



var timer = document.getElementById('stopwatch');


var today = new Date();

var sec = 0;
var min = 0;
var hr = 0;
var stoptime = true;

function startTimer() {
if (stoptime == true) {
stoptime = false;
timerCycle();

}
setCookie("Nikunj");
}
function stopTimer() {
if (stoptime == false) {
stoptime = true;
}
}

function timerCycle() {
if (stoptime == false) {
sec = parseInt(sec);
min = parseInt(min);
hr = parseInt(hr);

sec = sec + 1;


if (sec == 60) {
min = min + 1;
sec = 0;
}
if (min == 60) {
hr = hr + 1;
min = 0;
sec = 0;
}
if (hr == 24) {
day = day + 1;
hr = 0;
min = 0;
sec = 0;
}
if (hr > 12) {

hr = hr - 12;
}
if (sec <= 9 ) {
sec = '0' + sec;
}
if (min <= 9) {
min = '0' + min;
}
if (hr <= 9) {
hr = '0' + hr;
}

timer.innerHTML =hr +' : ' + min + ' : ' + sec ;
setTimeout("timerCycle()", 1000);
}
}
function resetTimer() {

timer.innerHTML = "00 : 00 : 00";
stoptime = true;
hr = 0;
sec = 0;
min = 0;
}


function setCookie(cname) {
const d = new Date()
let date = new Date().getTime()
d.setTime(d.getTime() + (2*24*60*60*1000));
let expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + date + ";" + expires + ";path=/";
}

function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);

}
}
return "";
}

function checkCookie() {
let startTimer = getCookie("Nikunj");

let dc = new Date().getTime();

if (startTimer != "") {
var difference = dc - startTimer;


var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60

var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60

var secondsDifference = Math.floor(difference/1000);


timer.innerHTML = hoursDifference + ' : ' + minutesDifference + ' : ' + secondsDifference;
stoptime = false;
sec = secondsDifference;
min = minutesDifference;
hr = hoursDifference;
timerCycle();

}
}








 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900