Simple JavaScript Countdown Timer

This tutorial will go over a simple dynamic countdown timer using JavaScript.

Example of a countdown timer using the code below

HTML + JavaScript

<p id="showDate"></p>
    <script>
        var countDownDate = new Date("Jun 18, 2019 17:37:00").getTime();
        var x = setInterval(function () {
        var now = new Date().getTime();
        var distance = countDownDate - now;
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
        document.getElementById("showDate").innerHTML = days + "d " + hours + "h "
                            + minutes + "m " + seconds + "s ";
         if (distance < 0) {
             clearInterval(x);
                        document.getElementById("showDate").innerHTML = "Times up!";
                    }
                }, 1000);
     </script>

Using the setInterval function, the data refreshes the distance between the inputted date and the current time every 1000 milliseconds (1 second). The getTime() function gets the number of milliseconds between January 1, 1970, and whatever date is inputted. So getting the number of milliseconds from proposed date minus the number of milliseconds at the current moment in time should give you the number of milliseconds between them. After you get that information, it's only a matter of simple math to get the days, hours, minutes, and seconds left. The information is then pushed onto the <p> tag with the id "showDate". Once the distance between both dates is less than 0, then instead of saying the date it will say "Times up!".

Comments

Post a Comment

Popular posts from this blog

Creating a Blockquote

SCAD Stylesheet Reference & Blog Intro