Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 210
user1881090 Avatar asked Dec 07 '12 13:12

user1881090


People also ask

Can I insert a timer in Canva?

To start the timer, click on the Play icon. To reset the timer, click on the Reset icon. To quickly add 1 minute to the time, click on +1 min.


2 Answers

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!

like image 131
alexmngn Avatar answered Sep 30 '22 23:09

alexmngn


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.

like image 36
Khez Avatar answered Sep 30 '22 23:09

Khez