How to create a timer

First of all, you have to convert your time in seconds.

<?php

list($hour,$min,$sec) = explode(':', $dbSessionDuration);
$dbSessionDurationTime = mktime(0,0,0,$hour,$min,$sec);

?>

To create a countdown, you have to use Javascript.

<script type="text/javascript">
    var millis = <?php echo $dbSessionDurationTime; ?>

    function displaytimer(){
        var hours = Math.floor(millis / 36e5),
            mins = Math.floor((millis % 36e5) / 6e4),
            secs = Math.floor((millis % 6e4) / 1000);
            //Here, the DOM that the timer will appear using jQuery
            $('.count').html(hours+':'+mins+':'+secs);  
    }

    setInterval(function(){
        millis -= 1000;
        displaytimer();
    }, 1000);

</script>

I didn't test, but that should work!


You should first know, that any JavaScript timer you create will be inaccurate. This is due to a myriad of reasons summed up very nicely here.

Now the beauty is, you can make limit the inaccuracy of your scripts by a simple check of the system time of the user on each iteration. Yes the system time of the user.

In your situation this is not a problem, because you're interested in elapsed time (01:30:10), but if you were waiting for a specific moment in time, you would need to handle time-zone differences or just a badly set clock on a user's computer.

What you also have to understand, is that if this is a problem of security, you will not be able to account for changes to the system clock post loading your script.

Example: Some sites force you to wait before doing a specific action. But changing your clock ahead, would in most cases help you bypass poor security. In most cases, it wouldn't because secondary checks are done server side. What I'm trying to say, is make those server side checks.


To answer your question, I would personally calculate the number of seconds that are required to pass:

$time = explode(':',$dbSessionDuration);# get hour, minutes, seconds to be elapsed
$time = $time[2] + $time[1] * 60 + $time[0] * 3600;# get elapse time in seconds

In your JavaScript file you could do something like this:

(function(endTime){
    endTime*=1000; // javascript works with milliseconds
    endTime+=new Date().getTime();// add the current system time into the equation
    // your timeSync function
    (function timerSync() {
        var diff = new Date(endTime - new Date().getTime());
        var timer=document.getElementById('timer');
        if(diff<=0)return timerEnd(timer);
        timer.innerHTML = 
            doubleDigits(diff.getUTCHours())
            + ':' +
            doubleDigits(diff.getUTCMinutes())
            + ':' +
            doubleDigits(diff.getUTCSeconds())
        ;
        setTimeout(timerSync,1000);
    })();// also call it to start the timer
    // your timer end function
    function timerEnd(timer) {
        timer.innerHTML='Timer has stopped now';
    }
    // double digit formatting
    function doubleDigits(number) {
        return number<10
            ? '0'+number
            : number
        ;
    } 
})(
    <?php echo $time;?>
);// time to elapse 1:30:10

Here is a working fiddle, but do remember. This is not optimized for your specific case. You could still wrap it up in an object, if you have two timers on the page, don't double up closure memory with functions that act absolutely the same.

If you have any questions, ask in a comment and I'll try to help.


Code: http://jsfiddle.net/g3rRJ/

I split the time into hours, minutes and seconds. and every second decremented the clock. Algo is pretty straight forward I believe:

var timer = setInterval(function(){
        seconds--;
        if(seconds == -1) {
            seconds = 59;
            minutes--;

            if(minutes == -1) {
                minutes = 59;
                hours--;

                if(hours==-1) {
                  alert("timer finished");
                  clearInterval(timer);
                  return;
                }
            }
        }
        span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
    }, 1000);