Search code examples
javascriptphpfunctiontimecountdown

PHP countdown, need it dynamic


I have a PHP-script that adds time into a SQL-DB like this:

    $howlong = 75; // Amount of seconds 
    $timetowait=time()+ $howlong; // This inserts into "timetowait" in SQL DB

Then to show my users how long they have to wait, I have this:

$timeleft= $rows['timetowait']; // This is the field in DB from above^
func_time($timeleft); // Function below, which shows the time left

The function above is:

function func_time($until){
$now = time();
$difference = $until - $now;
$seconds = $difference;
$output = "$seconds seconds";
return $output;
}

It works fine, but I want it to be a dynamic countdown. (Automaticly counting down, without refreshing the site) My problem here, is that I am using the "time()", and not pure text (f.ex 21/11/2013 20:00)


Solution

  • Usually this type of "countdown" like thing is handled by Javascript:

    On the client side you could do something like this:

    function countdown(seconds) {
        if(seconds > 0) {
            alert(seconds + ' Seconds Left');
            setTimeout(function(){
                countdown(--seconds);
            }, 1000);
        }
        else {
            alert('Time out!');
        }
    }
    

    Demo: http://jsfiddle.net/qwertynl/fn4MV/