Jump to content

Create dynamic countdown timer


mranton123
 Share

Recommended Posts

Why is this 'dynamic'?  And how do you want this to perform - as a background counter on the server to trigger some response or as a JS one that sits on the client and ticks off time for the user to see?

Questions, Questions, Questions.....

Link to comment
Share on other sites

The PHP DateTime::diff() method provides a very convenient way of getting the days, hours, minutes and seconds components of a time difference so this script uses an AJAX request on loading to get the time remaining. From then on, it calls a javascript function every second to reduce the time displayed by one second. This greatly reduces network traffic and gives a consistent update performance. Repeatedly using AJAX could sometimes result in delays preventing a regular countdown interval. 

<?php

##################################################################################################################
#                                                                                                                #
#    THIS SECTION HANDLES THE AJAX REQUEST AND EXITS TO SEND RESPONSE (Days,hrs, mins, secs remaining)           #
#                                                                                                                #
        if (isset($_GET['ajax'])) {
            if ($_GET['ajax'] == 'countdown') {
                $remain = ['days' => 0, 'hrs' => 0, 'mins' => 0, 'secs' => 0];
                $dt1 = new DateTime( $_GET['target'] );
                $dt2 = new DateTime('now');
                if ($dt1 > $dt2) {
                    $diff = $dt1->diff($dt2);
                    $remain['days'] = $diff->days;
                    $remain['hrs'] =  $diff->h;
                    $remain['mins'] = $diff->i;
                    $remain['secs'] = $diff->s;
                }
                exit(json_encode($remain));
            }
        }
#                                                                                                                 #
###################################################################################################################

$target = '2022-04-30 23:59:59';                         // SET OR GET TARGET TIME HERE


$targ = new DateTime($target);
$target_time = $targ->format('g:ia');
$target_date = $targ->format('F jS Y');

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Countdown</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>  
<script type='text/javascript'>
var inter

    $().ready( function() {
        get_time_remaining()                                      // call AJAX request to get remaining time
        inter = setInterval(countdown, 1000)                      // set timer to call "countdown()" function every second
    })
    
    function countdown()
    {
        let s = parseInt($("#secs").html())                      // get current time remaining
        let m = parseInt($("#mins").html())
        let h = parseInt($("#hrs").html())
        let d = parseInt($("#days").html())
        
        if (d==0 && h==0 && m==0 && s==0) {                      // exit when target time is reached
           clearInterval(inter)
           $(".remain").css("background-color", "red")
           return 
        }
        s--;                                                     // reduce display by 1 second
        if (s < 0) {
            s = 59;
            m--
        }
        if (m < 0) {
            m = 59
            h--
        }
        if (h < 0) {
            h = 23
            d--
        }
        if (d < 0) {
            d = 0
        }
                                                                 
        $("#days").html(d)                                       // redisplay new values
        $("#hrs").html(h)
        $("#mins").html(m)
        $("#secs").html(s)
    }
    
    function get_time_remaining()
    {
        $.get(                                                   // make AJAX request
            "",
            {"ajax":"countdown", "target":$("#target").val()},
            function(resp) {                                     // put response values in display fields
                $("#days").html( resp.days )
                $("#hrs").html( resp.hrs )
                $("#mins").html( resp.mins )
                $("#secs").html( resp.secs )
            },
            "JSON"
        ) 
    }
</script>
<style type='text/css'>
    body {
        font-family: verdana, sans-serif;
        font-size: 11pt;
    }
    header {
        padding: 8px;
        text-align: center;
        width: 600px;
        margin: 20px auto;
        background-color: #F0F0F0;
    }
    .target {
        color: #006EFC;
        font-size: 16pt;
    }
    table {
        border-collapse: collapse;
        width: 400px;
        margin: 0 auto;
    }
    td, th {
        padding: 8px;
        text-align: center;
        width: 25%;
    }
    .remain {
        font-size: 24pt;
        color: white;
        background-color: black;
        border: 1px solid white;
    }
</style>
</head>
<body>
    <header>
        <p>Countdown to</p>
        <p class='target'><?=$target_time?> on <?=$target_date?> </p>
        
        <!-- make target time available to javascript -->
        <input type='hidden' id='target' value='<?=$target?>' >
        
        <table border='0'>
            <tr><th>Days</th><th>Hours</th><th>Mins</th><th>Secs</th></tr>
            <tr>
                <td class='remain' id='days'>0</td>
                <td class='remain' id='hrs'>0</td>
                <td class='remain' id='mins'>0</td>
                <td class='remain' id='secs'>0</td>
            </tr>
        </table>
    </header>
</body>
</html>

image.png.ae51daea74559f2bb4f46eb2e6ba8b03.png

  • Like 2
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.