最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to create a timer - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Jan 16, 2013 at 2:36 user1881090 asked Dec 7, 2012 at 13:17 user1881090user1881090 7415 gold badges17 silver badges35 bronze badges 6
  • what you get var_dump($courseid) before insert query – GBD Commented Dec 7, 2012 at 13:23
  • have you selected any item into dropdown and then submit to php ? – GBD Commented Dec 7, 2012 at 13:56
  • can you paste your html form ? – GBD Commented Dec 7, 2012 at 14:25
  • The empty string will cast to an integer 0. – Michael Berkowski Commented Dec 7, 2012 at 14:36
  • Try data: $('#detailsForm').serialize()+'&courses='+$('#coursesDrop').val(), – GBD Commented Dec 8, 2012 at 5:04
 |  Show 1 more comment

7 Answers 7

Reset to default 14 +50

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!

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);

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.

Use jQuery as you own it.

Here is a nice plugin https://github.com/jylauril/jquery-runner

and this is an example of it:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
        <script src="https://raw.github.com/jylauril/jquery-runner/master/build/jquery.runner-min.js"></script>      
    </head>
    <body>
        <span id="runner"></span>

        <script type="text/javascript">
            $(document).ready(function(){
                $('#runner').runner({
                    autostart: true,
                    countdown: true,
                    stopAt: 0,
                    startAt: 30000 // alternatively you could just write: 30*1000
                });
            });
        </script>
    </body>
</html>

if you need a timer you can use this plugin in Jquery it works great. You'd just put The time or $dbSessionDuration in a hidden element of HTML after reading it and put it to jquery counter plugin. If the idea sounds interesting let me know and I leave an example.

You can do this more easy way. First You have to retrieve time from database which is already in seconds

<?php

    require_once 'db_connect.php';
    $sql = "SELECT * FROM ac_one_config"; 
    $result = $con->query($sql);

    if( $result->num_rows > 0 ){
        while($row=mysqli_fetch_assoc($result)) {
            $time_on = $row['ac_on_time'];
        }
    }
    header( "refresh:$time_on; url=https://localhost/your_project/file.php");

In Javascript the countdown start and countdown start from time $time_on until 0:00:00

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Massive Electronics</title>
    <style type="text/css">
        .myClass {
            font-family: verdana; 
            font-size: 16px; 
            font-weight: normal;  
            color: black;
            line-height: 30px;
        }
   </style>
 </head>
 <body>
     <script type="text/javascript">

        (function () {
            var timeLeft = <?php echo $time_on; ?>,
            cinterval;

            var timeDec = function (){
                timeLeft--;
                document.getElementById('countdown').innerHTML = timeLeft;
                if(timeLeft === 0){
                    clearInterval(cinterval);
                }
            };

            cinterval = setInterval(timeDec, 1000);
         })();

      </script>
      Redirecting in <span id="countdown"><?php echo floor($time_on); ?></span> seconds.<br><br>
      <span class="myClass">Ac ON Page</span>
    </body>
</html>

Set the time duration and store this value in session variable.

   <div id="timer"></div>
 <?php

      $_SESSION['TIME_DURATION'] = 45;
      $_SESSION['start_time'] = date("Y-m-d H:i:s");
      $end_time = date("Y-m-d H:i:s", strtotime('+'.$_SESSION['TIME_DURATION'].'minutes',strtotime($_SESSION['start_time'])));
      if(!isset($_SESSION['end_time']) && empty($_SESSION['end_time'])){
         $_SESSION['end_time'] = $end_time;
       }
 ?>

     var myVar = setInterval(myTimer, 1000);

     function myTimer() {
         var xmlhttp = new XMLHttpRequest();

         xmlhttp.open("GET","response.php",false);

         xmlhttp.send(null);

         if(xmlhttp.responseText == "Time Out"){

             myStopFunction();


        }
        $('#timer').html(xmlhttp.responseText);
     }


     function myStopFunction() {
          clearInterval(myVar);
     }

  1. File: response.php

    session_start();
    
    if(isset($_SESSION['TIME_DURATION']) && $_SESSION['TIME_DURATION'] != 0 ){
    
          $time_first = strtotime(date("Y-m-d H:i:s"));
    
         $time_second = strtotime($_SESSION['end_time']);
    
         $differenceinseconds = $time_second - $time_first;
    
         $time_lapse=gmdate("i:s",$differenceinseconds); 
         if($time_lapse=='00:00') { 
              echo "Time Out"; 
              unset($_SESSION['start_time']);
              unset($_SESSION['end_time']);
              unset($_SESSION['TIME_DURATION']);
         }else {
            echo gmdate("i:s",$differenceinseconds);
         }
    }else{
         echo "Time Out"; 
    }
    
发布评论

评论列表(0)

  1. 暂无评论