JavaScript Countdown Timer

Often on sites that sell something you can find a countdown timer to a certain date. Such a script is usually required for landing pages and online stores.

JS

(() => {
 
    let finishDate = new Date(2017, 8, 30); // set the final date
    let compareDate = finishDate.getTime();
 
    let timer = setInterval(function () {
        timeBetweenDates(compareDate);
    }, 1000);
 
    function timeBetweenDates(toDate) {
 
        let difference = toDate - Date.now();
 
        if (difference <= 0) { // if the date has passed, the timer stops
 
            clearInterval(timer);
 
        } else {
 
            let 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;
 
            if (days < 10) days = '0' + days;
            if (hours < 10) hours = '0' + hours;
            if (minutes < 10) minutes = '0' + minutes;
            if (seconds < 10) seconds = '0' + seconds;

            document.getElementById('days').innerHTML = days;
            document.getElementById('hours').innerHTML = hours;
            document.getElementById('minutes').innerHTML = minutes;
            document.getElementById('seconds').innerHTML = seconds;
 
        }
    }
})();

HTML

<div class="timer">
    <div class="timer-el">
        <div id="days"></div>
        <div class="timer-el__name">
            Days
        </div>
    </div>
    <div class="timer-el">
        <div id="hours"></div>
        <div class="timer-el__name">
            Hours
        </div>
    </div>
    <div class="timer-el">
        <div id="minutes"></div>
        <div class="timer-el__name">
            Minutes
        </div>
    </div>
    <div class="timer-el">
        <div id="seconds"></div>
        <div class="timer-el__name">
            Seconds
        </div>
    </div>
</div>

Let me remind you that months in JavaScript starts from zero 0.

// December 30, 2017
new Date(2017, 11, 30)

Comments

Popular posts from this blog

Closing a site with .htaccess

Typical gulpfile.js

JavaScript Inheritance and Classes