How to make a countdown timer in Javascript

If you need to advertise an event (like the launch of a new product) in your web site then you need a countdown timer. This post explains how to build one

Keep in ming that this is a very simple countdown timer made in HTML, CSS and Javascript but you can personalize it to your event by editing the CSS and HTML file.

    You can

    • Read the post if you want to know how to build otherwise..

    • if you are in a hurry pick it from JSFiddle here


    First prepare the HTML, note that the div where the countdown timer goes has an id called timer.

    					
    <div id = "imgdtm" align = "center">
    <br>
    <img src = "https://ibb.co/n89NLk"  alt = "banner of event">
    </div>
    <br>
    <div id="timer" align = "center" style = "font-size:40px;"></div>
    
    <div align = "center" style = "color : red;"><h1> Days left for the Great Event</h1></div>
    						
    						
    						

    Prepare the css file in particular for the timer div

    						
    #timer {
    font-size: 16px;
    font-family: 'Teko', sans-serif;
    width: 5OOpx;
    border: 1px solid rgba(255,255,255,.2);
    
    }
    						
    						

    Finally the Javascript code

    						
    var countDownDate = new Date("May 31,  2017  15:37:25").getTime();
    
    // refresh every 1 second the timer
    var x = setInterval(function() {
    
        // this will give you current date and time
        var now = new Date().getTime();
        
        // calculate how much time from now on the count down date
        var distance = countDownDate - now;
        
        // Time in days, hours, minutes and seconds
        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);
        
        // The result goes to an element with id="timer"
        document.getElementById("timer").innerHTML = days + "d -  " + hours + "h -  "
        + minutes + "m -  " + seconds + "s   ";
        
        // If the count down is over, write some text 
        if (distance < 0) {
            clearInterval(x);
            document.getElementById("timer").innerHTML = "EXPIRED";
        }
    }, 1000);
    						
    						

    Have a look at the JSFiddle embbeded below. It shows how the count down timer looks on the page.