Okan
Okan

Reputation: 1389

Timer countdown with javascript

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.

Upvotes: 1

Views: 146

Answers (3)

sg.cc
sg.cc

Reputation: 1826

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

Upvotes: 0

sEver
sEver

Reputation: 2305

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

Upvotes: 1

Robert Rossmann
Robert Rossmann

Reputation: 12139

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.

Upvotes: 0

Related Questions