How to Create a Countdown Timer with PHP and JavaScript

11 months ago admin PHP

In this lesson, we will see how to create a countdown timer with PHP and JavaScript, we will have three buttons start, stop and reset the countdown timer, so let's see how we can do that.


Create the index.php file

First, let's create the 'index.php' file here we have three buttons start, stop and reset the countdown timer, every button triggers a javascript method on click.

Also, we have a div where we display the timer countdown and the message when the timer finishes.

                                                        
                                                                                                                        
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>PHP JS Countdown Timer</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
    </head>
    <body class="bg-light">
        <div class="container">
            <div class="row my-5">
                <div class="col-md-8 mx-auto">
                    <div class="d-none my-3" id="message"></div>
                    <div class="card">
                        <div class="card-body d-flex flex-column justify-content-center">
                            <div class="row my-3 d-none" id="wrapper">
                                <div class="col-md-2 mx-auto">
                                    <span class="bg bg-dark text-white border border-white p-2 rounded shadow-sm" id="countdown"></span>
                                </div>
                            </div>
                            <div class="d-flex justify-content-center">
                                <button class="btn btn-success" onclick="startCountdown()">Start</button>
                                <button class="btn btn-danger mx-2" onclick="stopCountdown()">Stop</button>
                                <button class="btn btn-warning" onclick="reset()">Reset</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
        <script src="./script.js"></script>
    </body>
</html>

Create the script.js file

Next, let's create the 'script.js' file here we have the methods that will start, display, stop, and reset the countdown.

                                                            
                                                                                                                                
// Countdown duration in seconds
var timerDuration = 60;

var timerInterval;

// Start the countdown
function startCountdown() {
    // Clear intervals
    clearInterval(timerInterval);

    //Hide countdown finished message
    document.getElementById('message').classList.add('d-none');

    // Calculate the time
    var endTime = Math.floor(Date.now() / 1000) + timerDuration;

    // Run the countdown
    updateCountdown(endTime);

    // Update the countdown every second
    timerInterval = setInterval(function() {
        updateCountdown(endTime);
    }, 1000);
}

// Update the countdown 
function updateCountdown(endTime) {
    var currentTime = Math.floor(Date.now() / 1000);
    var remainingTime = endTime - currentTime;

    // Check if the countdown has finished
    if (remainingTime <= 0) {
        clearInterval(timerInterval);
        document.getElementById('wrapper').classList.add('d-none');
        document.getElementById('message').classList.remove('d-none');
        document.getElementById('message').innerHTML = `
            <div class="alert alert-info">
                Countdown finished!
            </div>
        `;
        return;
    }

    // Get the remaining hours, minutes, and seconds
    var hours = Math.floor(remainingTime / 3600);
    var minutes = Math.floor((remainingTime % 3600) / 60);
    var seconds = remainingTime % 60;

    // Format the countdown 
    var formattedTime = ('0' + hours).slice(-2) + ':' +
                        ('0' + minutes).slice(-2) + ':' +
                        ('0' + seconds).slice(-2);

    // Display the countdown
    document.getElementById('wrapper').classList.remove('d-none');
    document.getElementById('countdown').innerHTML = formattedTime;
}

// Stop the countdown
function stopCountdown() {
    clearInterval(timerInterval);
}

// Reset the countdown
function reset() {
    clearInterval(timerInterval);
    document.getElementById('countdown').innerHTML = '00:00:00';
}

Related Tuorials

How to Sort Associative Arrays in Descending Order According to the Key Value in PHP

in this lesson, we will see how to sort associative arrays in descending order according to the key...


How to Sort Associative Arrays in Ascending Order According to the Key Value in PHP

in this lesson, we will see how to sort associative arrays in ascending order according to the key v...


How to Sort Associative Arrays in Descending Order According to the Value in PHP

in this lesson, we will see how to sort associative arrays in descending order according to the valu...


How to Sort Associative Arrays in Ascending Order According to the Value in PHP

in this lesson, we will see how to sort associative arrays in ascending order according to the value...


How Do you Sort an Array in Descending Order in PHP

In this lesson, we will see how to sort descending an array in PHP, we will use the rsort() function...


How to Sort Ascending an Array in PHP

In this lesson, we will see how to sort ascending an array in PHP, we will use the sort() function t...


How to Remove a Key and its Value from an Associative Array in PHP

In this lesson, we will see how to remove a key and its value from an associative array in PHP,&nbsp...


How to Modify a Value in an Associative Array in PHP

In this lesson, we will see how to modify a value in an associative array in PHP, an Associative arr...


How to Add an Item to an Associative Array in PHP

In this lesson, we will see how to add an item to an associative array in PHP, an Associative array...


How to Add an Element to an Array in PHP

In this lesson, we will see how to add an element to an array in PHP, PHP has a built-in function th...