Countdown timer in javascript

In this programming tutorial you will learn how to develop the countdown timer in javascript. I have got the countdown timer code from internet but I have found lot of bugs in it during its testing process, after fixing those bugs I have decided to share it with you people. Following are the features of this countdown timer
  1. Cross browser compatibility.
  2. Doesn’t get unnecessary calls.
  3. Easy to implement.
  4. Work smoothly and perfectly.
Countdown timer in javascript
Just you have to do is to set a specific target date in the future, get the current date and then calculate the remaining time between them.

So let’s have a look over the example given below

Countdown timer in javascript

Countdown.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script> 
<script language="javascript" type="text/javascript">
function countdown(yr, m, d) {
            var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
            theyear = yr; themonth = m; theday = d
            var today = new Date()
            var todayy = today.getYear()
            if (todayy < 1000)
                todayy += 1900
            var todaym = today.getMonth()
            var todayd = today.getDate()
            var todayh = today.getHours()
            var todaymin = today.getMinutes()
            var todaysec = today.getSeconds()
            var todaystring = montharray[todaym] + " " + todayd + ", " + todayy + " " + todayh + ":" + todaymin + ":" + todaysec
            futurestring = montharray[m - 1] + " " + d + ", " + yr
            dd = Date.parse(futurestring) - Date.parse(todaystring)
            dday = Math.floor(dd / (60 * 60 * 1000 * 24) * 1)
            dhour = Math.floor((dd % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1)
            dmin = Math.floor(((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1)
            dsec = Math.floor((((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1)
   if (dday == 0 && dhour == 0 && dmin == 0 && dsec == 1) {
   alert("12");
                document.getElementById('days1').innerHTML = "-";
                document.getElementById('days2').innerHTML = "-";
                document.getElementById('hrs1').innerHTML = "-";
                document.getElementById('hrs2').innerHTML = "-";
    document.getElementById('min1').innerHTML = "-";
                document.getElementById('min2').innerHTML = "-";
    document.getElementById('sec1').innerHTML = "-";
                document.getElementById('sec2').innerHTML = "-";
                return
            }
            else {
                if (dday > 0 || dhour > 0 || dmin > 0 || dsec > 0) 
    {//Some time remaining
                    if (dday <= 0) 
     {//If we have time of less than a day
                        document.getElementById('days1').innerHTML = "-";
                        document.getElementById('days2').innerHTML = "-";

                    }
                    if (dday > 0 && dday < 10) 
     {
                        //IF day is let's suppose 9
                        document.getElementById('days1').innerHTML = 0;
                        document.getElementById('days2').innerHTML = dday;
                    }
                    else 
     {
                        //IF day is let's suppose >=10
                        var numDays = new Number(dday);
                        numDays = numDays.toString();
                        if (numDays.length == 1) 
      {
                            document.getElementById('days1').innerHTML = 0;
                            document.getElementById('days2').innerHTML = numDays.substring(0, 1);
                        }
                        else 
      {
                            document.getElementById('days1').innerHTML = numDays.substring(0, 1);
                            document.getElementById('days2').innerHTML = numDays.substring(1, 2);
                        }
                    }
                    //Day region Ends Here

                    //Hour Region Starts Here
     if (dhour <= 0) 
     {
                        document.getElementById('hrs1').innerHTML = "-";
                        document.getElementById('hrs2').innerHTML = "-";

                    }
                    if (dhour > 0 && dhour < 10) 
     {
                        document.getElementById('hrs1').innerHTML = 0;
                        document.getElementById('hrs2').innerHTML = dhour;
                    }

                    else 
     {
                        var numHrs = new Number(dhour);
                        numHrs = numHrs.toString();
                        if (numHrs.length == 1) 
      {
                            document.getElementById('hrs1').innerHTML = 0;
                            document.getElementById('hrs2').innerHTML = numHrs.substring(0, 1);
                        }
                        else 
      {
                            document.getElementById('hrs1').innerHTML = numHrs.substring(0, 1);
                            document.getElementById('hrs2').innerHTML = numHrs.substring(1, 2);
                        }
                    }
     //Hour Region Ends Here
     
     //Minute Region Starts Here
     if (dmin <= 0) 
     {
                        document.getElementById('min1').innerHTML = "-";
                        document.getElementById('min2').innerHTML = "-";

                    }
                    if (dmin > 0 && dmin < 10) 
     {
                        document.getElementById('min1').innerHTML = 0;
                        document.getElementById('min2').innerHTML = dmin;
                    }

                    else 
     {
                        var numMins = new Number(dmin);
                        numMins = numMins.toString();
                        if (numMins.length == 1) 
      {
                            document.getElementById('min1').innerHTML = 0;
                            document.getElementById('min2').innerHTML = numMins.substring(0, 1);
                        }
                        else 
      {
                            document.getElementById('min1').innerHTML = numMins.substring(0, 1);
                            document.getElementById('min2').innerHTML = numMins.substring(1, 2);
                        }
                    }
     //Minute Region Ends Here
     
     //Second Region Starts Here
     if (dsec <= 0) 
     {
                        document.getElementById('sec1').innerHTML = "-";
                        document.getElementById('sec2').innerHTML = "-";

                    }
                    if (dsec > 0 && dsec < 10) 
     {
                        document.getElementById('sec1').innerHTML = 0;
                        document.getElementById('sec2').innerHTML = dsec;
                    }

                    else 
     {
                        var numSecs = new Number(dsec);
                        numSecs = numSecs.toString();
                        if (numSecs.length == 1) 
      {
                            document.getElementById('sec1').innerHTML = 0;
                            document.getElementById('sec2').innerHTML = numSecs.substring(0, 1);
                        }
                        else 
      {
                            document.getElementById('sec1').innerHTML = numSecs.substring(0, 1);
                            document.getElementById('sec2').innerHTML = numSecs.substring(1, 2);
                        }
                    }
     //Second Region Ends Here
     setTimeout("countdown(theyear,themonth,theday)", 1000)
                }
    //Don't comment this below mentioned else statement
    //This statement is very much helpful when you will perform testing of this code by providing old date
    //This else statement will only executed when you provide old date as compared to current date
                else {
                    document.getElementById('days1').innerHTML = "-";
                    document.getElementById('days2').innerHTML = "-";
                    document.getElementById('hrs1').innerHTML = "-";
                    document.getElementById('hrs2').innerHTML = "-";
     document.getElementById('min1').innerHTML = "-";
                    document.getElementById('min2').innerHTML = "-";
                    document.getElementById('sec1').innerHTML = "-";
                    document.getElementById('sec2').innerHTML = "-";

                }

            }
        }
    $(document).ready(function () {
            countdown(2011, 12, 25);
        });

</script>

And here's the html code of this example that you will copy and paste in your web page
<div style="border: medium none; padding: 12px; margin: 0px 0px 480px 27px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 20px;font-family:verdana;">Days</div>

  <div style="border: medium none; padding: 12px; margin: 0px 0px 480px 157px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 20px;font-family:verdana;">Hrs</div>

<div style="border: medium none; padding: 12px; margin: 0px 0px 480px 280px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 20px;font-family:verdana;">Mins</div>

<div style="border: medium none; padding: 12px; margin: 0px 0px 480px 400px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 20px;font-family:verdana;">Secs</div>

<div style="border: medium none; padding: 12px; margin: 0px 0px 400px 27px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 50px;"
        id="days1"> </div>
<div id="days2" style="border: medium none; padding: 12px; margin: 0px 0px 400px 80px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px;
        "> </div>
<div id="hrs1" style="border: medium none; padding: 12px; margin: 0px 0px 400px 157px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px;
       "> </div>
<div style="border: medium none; padding: 12px; margin: 0px 0px 400px 212px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 50px;"
        id="hrs2"> </div>
<div id="min1" style="border: medium none; padding: 12px; margin: 0px 0px 400px 280px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px; 
         "></div>
<div id="min2" style="border: medium none; padding: 12px; margin: 0px 0px 400px 330px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px; 
         "></div>
<div id="sec1" style="border: medium none; padding: 12px; margin: 0px 0px 400px 400px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px; 
         "></div>
<div id="sec2" style="border: medium none; padding: 12px; margin: 0px 0px 400px 450px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px; 
         "></div>

This countdown timer function will give you countdown between current date, that it will pick from your system date, and the date mentioned in calling of countdown timer function which is countdown(2011, 12, 25);

You just have to replace this date with the date you desire for countdown time. I have used jquery’s $(document).ready(function ()) event because I want to execute this function when every DOM is loaded. But if you don’t want to use jquery and its ready event then exclude the jquery file and its code from the example and copy/paste following code just before </html> tag

<script language="javascript" type="text/javascript">
countdown(2011, 12, 25);
</script>

This technique is equivalent to jquery’s document.ready event.

I have used two divs for showing days, two divs for showing hours, two divs for showing minutes and again two divs for showing seconds. For example if remaining days are 14 then 1 will be store in days1 div and 4 will be stored in days2 div. You can use one div for showing remaining days, hours, minutes and seconds.

Moreover, I have applied all the checks in javascript code so that function will not get any extra call if countdown is finished, I have seen lot of code in internet that work perfectly but when countdown is finished but its code is still in web page then the countdown function gets extra and totally unnecessary calls but in my example I have taken care of this issue and avoid extra calls to the countdown timer function.

So that’s it.
I love your feedback.

0 comments: