Ad

Update Countdown Time In Javascript Every Second

- 1 answer

I have some PHP script that echos how much time is left until an event. The time is outputted in a format that looks like 23h 15m 4s

Here is my PHP code:

    $now = new DateTime();
    $future_date = new DateTime($res['post_time']); # post_time is the time of event
    $interval = $future_date->diff($now);
    $time_until = rtrim(sprintf("%s%s%s",
        $interval->h > 0 ? $interval->h . "h " : "",
        $interval->i > 0 ? $interval->i . "m " : "",
        $interval->s > 0 ? $interval->s . "s " : ""
        )
    ); # Format time to not have '0'
   echo "Time until event " . $time_until;

Is there a way to have the time update every second in Javascript? I imagine that the echo will look something like

echo "Time until event <span id='countdown'>" . $time_until . "</span>";

where the JS will do something with #countdown?

Ad

Answer

What you need to do is:

  • convert the received time from php to a variable. i would suggest and array like [ hour, minutes, seconds].
  • Use setInterval (functionExample, 1000).
  • In the setInterval function , you just decrease the seconds, minutes, and hours and update the span#countdown.

var time = "5h 10m",
    time_formatted = [0,0,0],
    time_array = time.split(' ');

time_array.forEach(function(element){
    var i = -1;
    if (element.indexOf('h') > -1){
        i = 0;   
    } else if (element.indexOf('m') > -1){
        i = 1;
    } else if (element.indexOf('s') > -1){
        i = 2;
    }

    if (i != -1)
     time_formatted[i] = parseInt(element.substring(0, element.length -1));

    });

console.log(time_formatted);

Ad
source: stackoverflow.com
Ad