Date Countdown Using Vanilla JavaScript

on in JavaScript Time & Date
Last modified on

A while ago, I coded several date countdowns for several promotions. These countdowns went straight inside a third-party popup solution, so they needed to be short and fast, and most important, have no dependencies.

Here’s one of these countdown JavaScripts, optimized for ES6.

See a live demo here.

HTML

<div id="countdown"></div>
<div id="countdown-elements">
    <span>hours</span>
    <span>minutes</span>
    <span>seconds</span>
</div>

JavaScript

function pad(n) {
    return n < 10 ? '0' + n : n;
}

function CountDownTimer(dt, id) {
    let end = new Date(dt),
        _second = 1000,
        _minute = _second * 60,
        _hour = _minute * 60,
        _day = _hour * 24,
        timer;

    function showRemaining() {
        let now = new Date(),
            distance = end - now;

        if (distance < 0) {
            clearInterval(timer);
            document.getElementById(id).innerHTML = 'EXPIRED!';

            return;
        }

        let days = Math.floor(distance / _day),
            hours = Math.floor((distance % _day) / _hour),
            minutes = Math.floor((distance % _hour) / _minute),
            seconds = Math.floor((distance % _minute) / _second);

        document.getElementById(id).innerHTML = pad(hours) + '<span>:</span>' + pad(minutes) + '<span>:</span>' + pad(seconds);
    }

    timer = setInterval(showRemaining, 1000);
}

CountDownTimer('12/27/2020 10:1 AM', 'countdown');

CSS

#countdown {
    width: 200px;
    background-color: #FFFFFF;
    text-align: center;
    font-size: 48px;
}
#countdown-elements {
    width: 200px;
    background-color: #FFFFFF;
    text-align: center;
}
#countdown-elements span {
    font-size: 10px;
    text-transform: uppercase;
    display: inline-block;
    padding: 0 8px;
}

Optionally, I used Google’s Closure Compiler to minify the code, which now looks like this:

function pad(b){return 10>b?"0"+b:b}function CountDownTimer(b,c){var d=new Date(b);var e=setInterval(function(){var a=d-new Date;if(0>a)clearInterval(e),document.getElementById(c).innerHTML="EXPIRED!";else{var f=Math.floor(a%864E5/36E5),g=Math.floor(a%36E5/6E4);a=Math.floor(a%6E4/1E3);document.getElementById(c).innerHTML=pad(f)+"<span>:</span>"+pad(g)+"<span>:</span>"+pad(a)}},1E3)};

Use it wherever you need, by calling the function:

CountDownTimer('12/27/2020 10:1 AM', 'countdown');

You can have multiple countdowns on one page, by using multiple HTML element IDs.

Related posts