Skip to content
Advertisement

How to create a timer

I have a $dbSessionDuration variable where by using mysqli, it is able to bind the result of data from the query into this variable. The $dbSessionDuration variable holds time so the variable has a time format as below:

01:30:10

Now that means 1 hour 30 mins and 10 seconds. What I want to do is display $dbSessionDuration value in a timer so that in above’s example it will start ticking down from 01:30:10 and go all the way to 0 when it stops. My question is how do you create timer and place whatever value $dbSessionDuration value in the timer to count down to 00:00:00?

Advertisement

Answer

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!

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement