I have a timer countdown with javascript.It countdowns from 3 minutes.But if user reloads the page I have to resume the countdown.I mean user loaded the page and countdown starts from 3 minutes then after 1 minute user reloads the page countdown should start from 2 minutes.How can I do this ? I don't want any code I need the algorithm.
-
You have to store the time of the first load either in local storage or the server and use that to figure out from where to start the countdownyts– yts2015-04-16 13:22:10 +00:00Commented Apr 16, 2015 at 13:22
-
If you want it to persist, use localStorage or sql database to track the start time.taesu– taesu2015-04-16 13:22:16 +00:00Commented Apr 16, 2015 at 13:22
-
Do you want to do directly from frontend or it involves backend too?Endre Simo– Endre Simo2015-04-16 13:23:36 +00:00Commented Apr 16, 2015 at 13:23
-
I think it's possible to set count down to certain date. So it's always counting time that's left. Maybe this info will help you.Dashovsky– Dashovsky2015-04-16 13:27:10 +00:00Commented Apr 16, 2015 at 13:27
3 Answers
After each second change, you need to save the state of the counter into some kind of persistent storage.
I'd just use:
localStorage['time_left'] = JSON.stringify(time_left);
When you load the page, first you try to load the state of the timer.
time_left = JSON.parse(localStorage['time_left']);
And then check whether the value was even stored.
if(time_left===undefined){// you're on fresh instance
Would also be good idea to clear the stored variable after the timer finishes.
Good luck :>
Comments
You need to persist the current time left to the end of the timer somewhere where you can access it later, even after the page has been refreshed. Local storage comes to mind, but other methods may be possible.
Instead of setting the timer to 3 minutes, you set an interval to run a function every second. You save two pieces of information to your storage:
- Amount of time till the end, perhaps in seconds ( 180s for 3 minutes)
- Amount of time already passed since the start (0 by default, incremented with each interval)
Every time the interval function ticks, you increase the total time passed and check if it is already higher than the total amount expected. Do your custom actions when the condition is true. Do not forget to clear the interval, otherwise it will keep going on indefinitely and uselessly.
Comments
var remaining = localStorage.remaining || 180;
window.setInterval(function(){
remaining = remaining - 1;
document.querySelector('#countdown').innerHTML = remaining;
}, 1000);
window.onbeforeunload = function(){
// Save remaining time as the window is closed or navigated elsewhere
localStorage.remaining = remaining;
};