On my webpage I have a timer, it has to run all the time, but when the page refreshes the timer resets to 0. Guide me how to achieve this.
var hours =0;
var mins =0;
var seconds =0;
$('#start').click(function(){
startTimer();
});
$('#stop').click(function(){
clearTimeout(timex);
});
$('#reset').click(function(){
hours =0;
mins =0;
seconds =0;
$('#hours','#mins').html('00:');
$('#seconds').html('00');
});
function startTimer(){
timex = setTimeout(function(){
seconds ;
if(seconds >59){
seconds=0;mins ;
if(mins>59)
{
mins=0;
hours ;
if(hours <10) {
$("#hours").text('0' hours ':');
}
else {
$("#hours").text(hours ':');
}
}
if(mins<10){
$("#mins").text('0' mins ':');
}
else {$("#mins").text(mins ':');
}
}
if(seconds <10) {
$("#seconds").text('0' seconds);
} else {
$("#seconds").text(seconds);
}
startTimer();
},1000);
}
#timer {
font-size:150px;
margin:0 auto;
width:1000px;
}
#controls {
margin:0 auto;
width:600px;
}
#controls button {
font-size:24px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<center>
<div id="timer">
<span id="hours">00:</span>
<span id="mins">00:</span>
<span id="seconds">00</span>
</div>
<div id="controls">
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
</div>
</center>
Thanks in advance...!
CodePudding user response:
For that, you should use a local-storage, or any technology to save data locally in the browser.
localStorage.setItem('timer', your_time_var);
In there you have documentation how to use that: https://developer.mozilla.org/pl/docs/Web/API/Window/localStorage
CodePudding user response:
You should store your timer before page load.
Use localStorage
and onbeforeunload
event