1

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.

4
  • 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 countdown Commented Apr 16, 2015 at 13:22
  • If you want it to persist, use localStorage or sql database to track the start time. Commented Apr 16, 2015 at 13:22
  • Do you want to do directly from frontend or it involves backend too? Commented 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. Commented Apr 16, 2015 at 13:27

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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:

  1. Amount of time till the end, perhaps in seconds ( 180s for 3 minutes)
  2. 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

0
  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;
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.