Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

How to create a Javascript timer countdown?

Javascript countdown timer

Let’s create a few examples of Javascript timer countdown. In our first example, we’ll create a simple Javascript count down from 10 seconds.

Simple Javascript timer countdown example 1

Here is a screenshot of the JS timer countdown from 10 seconds. We have used Bootstrap CSS for designing text and buttons. We create a countdown timer in Javascript, clicking on the button start will start the timer countdown from 10 seconds. In this example, we use the setInterval() function to add count down from 10 seconds.

Javascript timer countdown example
Simple timer countdown
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
    #timerCountDown {
        text-align: center;
        padding: 4px;
        font-size: 2em;
        width: 150px;
        color: #fff;
        background-color: #1100ff;
        border: 1px solid #1b0fc0;
        border-radius: 5px;
    }
</style>

<body>
    <div class="container mt-3">
        <h4>Count down time from 10 second</h4>
        <p id="timerCountDown" class="lead">
            Start
        </p>
    </div>


    <script>
        const timerElement = document.getElementById('timerCountDown');
        let timer;

        function startTimeCountDown() {
            timer = 10;
            const timeCountdown = setInterval(countdown, 1000);
        }


        function countdown() {
            if (timer == 0) {
                clearTimeout(timer);
                timerElement.innerHTML = 'Start'

            } else {
                timerElement.innerHTML = timer + ' secs';
                timer--;
            }
        }

        timerElement.addEventListener('click', ev => {
            startTimeCountDown();
        });
    </script>
</body>

</html>

Javascript day countdown timer

In our second JS timer countdown, we have days, hours, minutes, and second on Javascript day countdown. Here is a screenshot of the Javascript countdown timer seconds example.

Javascript day countdown
Javascript countdown timer seconds
<!DOCTYPE HTML>
<html>

<head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <style>
        div.timerContainer {
            text-align: center;
            padding: 5px;
            width: 550px;
            color: #fff;
            background-color: #1100ff;
            border: 1px solid #1b0fc0;
            border-radius: 5px;
        }

        #timer {
            font-size: 2.2em;
        }
    </style>
</head>

<body>
    <div class="container mt-4">
        <div class="timerContainer">
            <h4>Some one special birthday on : 06-July-2022</h4>
            <p>Number of day, hour, minute and second left to celebrate</p>
            <p id="timer"></p>
        </div>

    </div>


    <script>
        const countDownDate = new Date("Jul 6, 2022 00:00:00").getTime();

        const timeCountdown = setInterval(() => {

            // Get current Time
            const now = new Date().getTime();

            // Difference bt countDownDate and now
            const timeDifference = countDownDate - now;

            // Time calculations for days, hours, minutes and seconds
            const millisecondInDay = 1000 * 60 * 60 * 24;
            const millisecondInHour = 1000 * 60 * 60;
            const millisecondInMinute = 1000 * 60;

            const days = Math.floor(timeDifference / millisecondInDay);
            const hours = Math.floor((timeDifference % millisecondInDay) / millisecondInHour);
            const minutes = Math.floor((timeDifference % (millisecondInHour)) / millisecondInMinute);
            const seconds = Math.floor((timeDifference % (millisecondInMinute)) / 1000);

            document.getElementById("timer").innerHTML = days + "d - " + hours + "h - "
                + minutes + "m - " + seconds + "s ";


            if (timeDifference < 0) {
                clearInterval(timeCountdown);
                document.getElementById("timer").innerHTML = "Sorry count down is expired";
            }
        }, 1000);
    </script>
</body>
</html>

Timer countdown with second

In our last example, we have added Javascript countdown timer seconds, minutes, hours, and days. Here is a screenshot of our example. In this example, we count the number of days, hours, minutes, and seconds left from now to 6-July-2022. We also added two buttons on our Javascript day counter.

  1. The start button will start our timer countdown.
  2. Pause the button to clear the timer reference and stop the timer countdown..
Javascript countdown timer example 3
Javascript countdown timer example 3
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
    .timer-bg {
        background: #654ea3;
        background: -webkit-linear-gradient(to right, #654ea3, #eaafc8);
        background: linear-gradient(to right, #654ea3, #eaafc8);
        width: 500px;
        border-radius: 1rem;
    }

    .heading,
    .times {
        display: flex;
    }

    .heading p,
    .times p {
        width: 100px;
        font-family: Lato;
        margin: 10px 0 0 0;
        text-align: center;
    }
    .times {
        font-size: 22px;
    }

    button {
        margin:5px;
    }
</style>

<body>
    <div class="container">
        <h4>Someone special birthday on : 06-July-2022</h4>
        <p>Number of day, hour, minute and second left to celebrate</p>


        <div class="timer-bg text-white shadow p-5 text-center mb-5">
            <div class="mb-0 font-weight-bold text-uppercase">
                <div class="heading">
                    <p>Days</p>
                    <p>Hours</p>
                    <p>Minutes</p>
                    <p>Seconds</p>
                </div>
                <div class="times">
                    <p id="days"></p>
                    <p id="hours"></p>
                    <p id="mins"></p>
                    <p id="seconds"></p>
                </div>
            </div>
            <div class="btnGroups mt-4">
                <button type="button" id="startBtn" class="btn btn-light">Start</button>
                <button type="button" id="pauseBtn" class="btn btn-light">Pause</button>
            </div>


        </div>
    </div>


    <script>
        let timeCountdown;
        function dateCountDown() {
            timeCountdown = setInterval(() => {
                currentDate = new Date();
                targetDate = new Date(2021, 12, 18);
                cDateMillisecs = currentDate.getTime();
                tDateMillisecs = targetDate.getTime();
                difference = tDateMillisecs - cDateMillisecs;
                seconds = Math.floor(difference / 1000);
                minutes = Math.floor(seconds / 60);
                hours = Math.floor(minutes / 60);
                days = Math.floor(hours / 24);

                hours %= 24;
                minutes %= 60;
                seconds %= 60;
                hours = hours < 10 ? "0" + hours : hours;
                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;

                document.getElementById("days").innerText = days;
                document.getElementById("hours").innerText = (Number(hours) + 6).toString();
                document.getElementById("mins").innerText = minutes;
                document.getElementById("seconds").innerText = seconds;
            }, 1000);

        }


        document.getElementById("pauseBtn").addEventListener("click", () => {
            clearInterval(timeCountdown);
        });

        document.getElementById("startBtn").addEventListener("click", () => {
            dateCountDown();
        });

    </script>
</body>

</html>

Use Javascript clearInterval() to stop setInterval

The setInterval() method continues executing, we need to stop the setInterval method by using the clearInterval() method in reference to the variable where set setInterval.

Most the modern browsers supported clearInterval() methods are listed below:

  1. Google Chrome 1.0
  2. Microsoft Edge 4.0
  3. Firefox 1.0
  4. Safari 1.0
  5. Opera 4.0

Related posts

How to create a Javascript timer countdown?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top