0

i have a question regarding a countdown timer. i have the below code that displays a visual countdown. my problem is that it resets everytime i refresh the page , its client-side. is there a way to make the below server side and restart when it reaches zero?

<script>
    var interval;
    var minutes = 1;
    var seconds = 5;
    window.onload = function() {
        countdown('countdown');
    }

    function countdown(element) {
        interval = setInterval(function() {
            var el = document.getElementById(element);
            if(seconds == 0) {
                if(minutes == 0) {
                    el.innerHTML = "countdown's over!";                    
                    clearInterval(interval);
                    return;
                } else {
                    minutes--;
                    seconds = 60;
                }
            }
            if(minutes > 0) {
                var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
            } else {
                var minute_text = '';
            }
            var second_text = seconds > 1 ? 'seconds' : 'second';
            el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
            seconds--;
        }, 1000);
    }
    </script>

<div id='countdown'></div>

the above code can be found here :
Javascript Countdown

Community
  • 1
  • 1
user631756
  • 55
  • 2
  • 9

2 Answers2

0

Just set

var minutes = 1;
var seconds = 5;

by the server script based in the end time of the countdown.

Example:

  1. Store datetime of the moment the countdown is over on the server side (PHP session)
  2. Calculate time for the countdown based on the stored value regarding the offset of the client (different timezone)
  3. Write to calculated values as JavaScript values in the output HTML

On reload, simply recalculate the time for the countdown again base on the stored value.

That's it!

CodeZombie
  • 5,367
  • 3
  • 30
  • 37
  • I believe the trick is for the server to know where the countdown script was when the browser navigated away or closed. – Jared Farrish Dec 19 '11 at 02:07
0

Are you sure the counter must be on server side? If you simply want the countdown to persist across browser refresh you can use cookie

// Setting cookie after every second, using the jQuery cookie plugin http://plugins.jquery.com/project/cookie
$.cookie("minutes", current_minutes_left);
$.cookie("seconds", current_seconds_left);

// Retrieve cookie later
$.cookie("minutes");
$.cookie("seconds");
// do something with the cookies

That should do it.

Tony
  • 36,591
  • 10
  • 48
  • 83