Date Countdown Using Vanilla JavaScript

πŸ™‚ Like
πŸ™‚Like πŸ₯°Love 🧐Watching this 🀨Suspicious πŸ˜’Meh 😑Angry

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.


<div id="countdown"></div>
<div id="countdown-elements">


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,

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

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


        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');


#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.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Friday, October 2, 2020 in Blog, JavaScript

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started

Related Articles

%d bloggers like this:
Privacy Policy