5 Apr 2014

Creating JavaScript CountDown Timer

CountDown Timers can be useful for many online things like displaying deadline for 'a limited deals' or 'a form submission date'.
In this tutorial we will learn how to develop and implement a simple Pure JavaScript CountDown Timer. Our Final emphasis will be only on JavaScript because display styles can be changed using any custom CSS.
If you are using my css then final result will look something like following image,


So lets get started,

- First of all create a element where you want to display final result.Give each element ID as per required result, for example, 'days','hours','minutes','seconds'
<div class="countDown">
           <span id="days">00</span>     <!-- Remaining Days,id="days"-->
           <span id="hours">00</span>    <!-- Remaining hours ,id="hours"-->
           <span id="minutes">00</span>  <!-- Remaining minutes,id="minutes"-->
           <span id="seconds">00</span>  <!-- Remaining secounds,id="secounds"-->
</div>

- Include .js file,which we will create, having code for countdown,Example, my file is countdown.js, which is in same directory.
<script src="countdown.js"></script> 
- Now call countdown function with end time and callback function name as parameters.[remember, input date format, 'mm/dd/yyyy hh:mm:ss AM/PM']
<script>
           
  countdown('04/05/2014  00:45:00 PM',callback); // Date format ('MM/DD/YYYY  HH:MM:SS TT');
            
  function callback(){
       alert('Time Out'); //Callback Function Definition

  };
</script>
now we will create our countdown function,following below mentioned key concepts,
i. get current time
ii. subtract from End time [input value]
iii. convert remaining time [milliseconds] in days,hours,minutes,seconds [or add years,months, if you want]
iv. repeat step (iii) every second till remaining time is greater then or equals to zero.

//JavaScript Function for CountDown Timer, In countdown.js file 

function countdown(endT,callback) {
        var days,hours,minutes,sec,timer;
        
        end = new Date(endT);
        
        end = end.getTime(); //Get initial Date in Milliseconds,
        if (isNaN(end)) {
           alert('@ countdown.js @  "Invalid Date", valid format- mm/dd/yyyy hh:mm:ss TT ');
           return;
        }
        
        timer = setInterval(calculate,1000);//Timer to calculate remaining time

        function calculate(){
         var current = new Date();
         var remaining = parseInt((end - current.getTime())/1000);//remaining seconds, 
          
            if (remaining <= 0){
                clearInterval(timer);
                days=0;
                hours=0;
                minutes=0;
                sec=0;
                display(days,hours,minutes,sec);
                if (typeof callback === 'function' ) {
                    callback();
                }
                
            }else{
                
                days = parseInt(remaining/86400);
                remaining = (remaining%86400);
                hours = parseInt(remaining/3600);
                remaining = (remaining%3600);
                minutes = parseInt(remaining/60);
                remaining = (remaining%60);
                sec = parseInt(remaining);
                display(days,hours,minutes,sec);
                
                
            }
        }

        //Function For displaying Results in HTML page with specific ID's 
        function display(days,hours,minutes,sec) {
            var dl = days.toString().length;
            if (dl == "1") {
                sl = 2;
            }else{
                if (isNaN(dl)) {
                    sl = 3;
                }
                sl = dl;
            }
            document.getElementById("days").innerHTML = ("00"+days).slice(-sl);
            document.getElementById("hours").innerHTML = ("0"+hours).slice(-2);
            document.getElementById("minutes").innerHTML = ("0"+minutes).slice(-2);
            document.getElementById("seconds").innerHTML = ("0"+sec).slice(-2);
        }
     
    }
Finally our CountDown timer is ready and result will look something like following texts,
00 01 04 41
Add some css to make it look pretty, Below is css code to decorate above result text, use this or create your own.
/* CSS for CountDown Timer,Notice I have added labels (days,hours,minutes,seconds) using :After pseudo class, you can add these in HTML itself*/ 
            .countDown{
                display: inline-block;
                margin: auto;
            }
           
            .countDown span{
                display: block;
                background: #000;
                color: #fff;
                height: 54px;
                float: left;
                margin-right: 5px;
                padding: 8px;
                border-radius: 5px;
                font-size: 45px;
                line-height:normal;
                text-align: center;
                box-shadow: 2px 2px 8px #747474;
                background-image: url("http://goo.gl/7IC8sK");/*If You want image background*/
                background-size: contain;                     /*If You want image background*/
                background-repeat: repeat-x;                  /*If You want image background*/
            }
            
            #days:after,#hours:after,#minutes:after,#seconds:after{
                
                font-size: 14px;
                line-height:normal;
                display: block;
                width: inherit;
                margin-top: 10px;
                color: #5C5757;
                text-align: center;
            }
            #days:after{
                content: "Days";
            }
            #minutes:after{
                content: "Minutes";
            }
            #hours:after{
                content: "Hours";
            }
            #seconds:after{
                content: "Seconds";
            }
working Demo,
Time Remaining for :

00 00 00 00
Did you find this post useful? Let Us know in the comments section below.

2 comments:

  1. I'm trying to get this to let me input the date for the countdown. Can you help me?

    ReplyDelete
  2. Change Date in countdown function call ap per required.
    For example you want to set this timer for May 31, 2015 , then change countdown function parameters as follows,
    countdown('05/31/2015 10:00:00 AM',callback); // countdown till May 31,10am

    ReplyDelete