Science Geek
Science Geek

Reputation: 71

Java Script Count Down Timer resets whenever page refreshes

I have PHP page, where I added a countdown for 30 min. and as it ticks when I refresh the page or perform a query of 'insert' and redirect back to that page, the timer gets reset.

I want the timer to be constant and continue count without any interruptions when the page gets refreshed.

My code goes as:

function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      timer = duration;
    }
  }, 1000);
}

window.onload = function() {
  var fiveMinutes = 60 * 30,
    display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timer">
  <div>Section</div>
  <div class="time">
    <strong>Time left: <span id="time">30:00</span></strong>
  </div>
</div>

Any Help Is Appreciated..

Upvotes: 1

Views: 123

Answers (5)

Fadi Tash
Fadi Tash

Reputation: 112

As others have pointed out, you could use local storage (if the your target clients support this feature see here)

<script>
        function startTimer(duration, display) {
            var timer = duration, minutes, seconds;

          setInterval(function () {
                minutes = parseInt(timer / 60, 10)
                seconds = parseInt(timer % 60, 10);

                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;

                display.textContent = minutes + ":" + seconds;
                timer = --timer;
                if (timer >= 0) {
                    localStorage.setItem('time', timer);
                    //timer = duration;
                }
            }, 1000);
        }

        window.onload = function () {
            var countDown = 60 * 30;
            var oldVal = localStorage.getItem('time');
            if (oldVal && oldVal > 0) {
                countDown = oldVal;
            }
            var display = document.querySelector('#time');
            startTimer(countDown, display);
        };
</script>

edit: of course one must not forget to check whether the stored value is below zero.

Upvotes: 1

Isac
Isac

Reputation: 1874

As already pointed out, you could store the current time with localStorage. To do so you would save both minutes and seconds in each interval tick:

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        localStorage.setItem("minutes", minutes); // <--
        localStorage.setItem("seconds", seconds); // <--

And in the load function you'd read from them and set the starting value appropriately. It's important to note that values are always stored as strings, and as such, it would be necessary to parse them back to numbers before passing them through:

window.onload = function () {
    var timeLeft = 60 * 30,
        display = document.querySelector('#time');

    var minutes = localStorage.getItem("minutes"); //read minutes
    var seconds = localStorage.getItem("seconds"); //read seconds

    if (minutes && seconds){
        timeLeft = Number(minutes) * 60 + Number(seconds); //set time with val from storage
    }

    startTimer(timeLeft, display);
};

I changed the name of your fiveMinutes to timeLeft to better reflect what it holds, and parsed both values to numbers with Number().

It's also important to mention that while this does keep the value after refreshes, it doesn't "count" the time while the page was closed. So keep that in mind.

Upvotes: 0

com
com

Reputation: 395

Whenever your PHP page loads, the javascript is loaded with it. So

window.onload = function () {
    var fiveMinutes = 60 * 30,
    display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};

is called and the timer starts at 5 minutes.

One solution would be to do an Ajax request in window.onload and get the remaining time.

Another solution would be to set the fiveMinutes variable (obviously it should be renamed more appropriately) via PHP, if the javascript code is inside your PHP file, like

<script>
...
var timeLeft = <?php echo $timeLeft ?>;
...
</script>

The first solution is the standard way to go and the second one is the easy way to go.

Upvotes: 1

m4gic
m4gic

Reputation: 1513

Instead of refreshing the whole page try to use Ajax for communication and modify your html page using javascript.

Upvotes: -1

M14
M14

Reputation: 1810

Use html5 local storage to update the timer value and when page load occurs read the timer value from local storage. I guess no other way.

Upvotes: 1

Related Questions