Few days back, I had to implement a simple count down timer at client side using javascript, that counts for specific minutes and does some action when the countdown expires. Since i had less time to write my own code, I just searched out for some plugins and used it in my app. But I found that there was some problem when I stop counting it manually, and reset it and again start it and the combination of these operations!
I changed my mind to implement my own. It worked well!!
Right now I have implemented it to count for only few minutes as that was the requirement at that time for me. I am sure that it can be extended to implement to count for hours, days months and years as the concept behind implementation fairly simple!
Input: Number of milli seconds to count down! (Say if u need to count down for 5 mins, it will be 5*60*1000.
Functionalities: Start, pause and restart(Reset) counter.
The logic flows as below: initialize the number of milli seconds to be counted to numMilliSecs On starting the counter, Set the targetTime: = current System time in milli seconds + numMilliSecs to be counte - This means that, the counter has to stop when the system's time reaches the targetTime Call the method that counts the time Method to count the time: If the difference between the targetTime and current System Time is greater than 0 { Display the difference (that u get in milli seconds) by converting it into minutes and seconds. Repeat the if statment above afer one second (In my code, I am repeating it on every 10 milli seconds so as to reduce any delay that maight be caused by the system time). } else { perform the post - counting operation if any!! }
Here we go for the code Now! Starting with the HTML! Here are the place holders of 2 digits of minutes and 2 digits of seconds and the buttons to operate the counter
<table> <tr> <td width="25%"> <input type="button" id="startButton" value="Start count!" onclick="doTimer();" /> </td> <td width="25%"> <input id="resetButton" type="button" value="Reset count!" onclick="resetCount();" style="display:none;"/> </td> <td width="25%"> <input id="pauseButton" type="button" value="Pause count!" onclick="pauseCount();" style="display:none;" /> </td> <td width="25%"> <input type="button" id="endButton" value="End Counter!" onclick="endCount();" style="display:none;" /> </td> </tr> </table> <div id="countdown"> <div class="dash minutes_dash"> <div class="digit" id="min0">0</div> <div class="digit" id="min1">0</div> </div> <div class="dash seconds_dash"> <div class="digit" id="sec0">0</div> <div class="digit" id="sec1">0</div> </div> </div>
We also need CSS for beautification!! Here we go
<style type="text/css"> #countdown{ height: 30px; } .dash { width: 60px; height: 30px; float: left; margin-left: 5px; position: relative; padding-top:5px; } .dash .digit { font-size: 26px; font-weight: bold; float: left; background: #09f; width: 28px; text-align: center; font-family: arial; color: #fff; position: relative; border:1px solid #000; } </style>
Lets enter into the core part where we implement our logic. I am using jQuery plugin to just hide and show the buttons.
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript"> /* Gloabal variables that we need! */ var t; /* Holds some ID that is returned by setTimeout method which is used to create some delay */ var timer_is_on=0; /* Specifies whether timer is running ot not */ var targetTime; /* Holds the target time in milliseconds to count */ var milliSecondsToCount = 120*1000; var resetTime = milliSecondsToCount; /* Value needed when we need to reset the counter since we modify the targetTime in later point when we need to pause the counter. */ /*Methods to implement the counter */ function doTimer() { if (!timer_is_on) /* If timer is not running already!! */ { timer_is_on=1; $("#endButton, #pauseButton,#resetButton").show(); /* Show the buttons for pause, reset and end timer when the counter starts */ $("#startButton").hide(); /* Hide the start counter button as it is gonna start now! */ targetTime = new Date().getTime()+milliSecondsToCount; /*Initialize the target time to current time + number of milliseconds to count */ countDownTime(); /* Start the counting process */ } } function countDownTime() { var difference=0; curTime= new Date().getTime(); difference = targetTime-curTime; /* Find the difference of target and current time */ if(difference >= 0) { displayTime(difference); /* Display the difference time */ t=setTimeout("countDownTime()",10); /* Wait for 10 milli seconds and call the method recursively The value can be anything between 1 and 1000. */ } else { /* If the control reaches here, it means that counter is expired. Perform the post counting operations */ $("#endButton, #pauseButton, #resetButton").hide(); $("#startButton").show(); clearTimeout(t); timer_is_on=0; milliSecondsToCount = resetTime; alert("I am done"); } } function displayTime(milliSecs) { var seconds = Math.floor(milliSecs/1000); /* Round of the milliSeconds to seconds.*/ /* Convert the seconds to mins: secs format Eg: 130 seconds = 02 mins : 10 secs.*/ /* formatTime method is used to make the values 2 digits i.e 2 mins sould be displayed as 02. I am using it to reduce number if else statements.*/ var mins= formatTime(Math.floor(seconds/60)); var secs = formatTime(seconds%60); /* Display the values in appropriate plave holders */ var min0= mins.charAt(0); var min1= mins.charAt(1); var sec0= secs.charAt(0); var sec1= secs.charAt(1); $('#min0').html(min0); $('#min1').html(min1); $('#sec0').html(sec0); $('#sec1').html(sec1); } function formatTime(i) { /* If the value of i is less than 10, then prepend 0 to it. */ var ret=""+i; if (i < 10) ret="0" + ret; return ret; } /*Remaining methods to handle the button click events */ function resetCount() { clearTimeout(t); /* Kill the current Timer */ timer_is_on=0; displayTime(milliSecondsToCount); milliSecondsToCount = resetTime; /*Reset the milli seconds to count */ doTimer(); /* Start the timer */ } function pauseCount() { $("#pauseButton").hide(); $("#startButton").show(); clearTimeout(t); /*Kill the current timer */ timer_is_on=0; curTime= new Date().getTime(); milliSecondsToCount = Math.floor((targetTime-curTime)); /* Set the milliSeconds to count to the remaining seconds to count */ } function endCount() { $("#endButton, #pauseButton, #resetButton").hide(); $("#startButton").show(); clearTimeout(t); timer_is_on=0; milliSecondsToCount = resetTime; displayTime(0); } window.onload= function(){ displayTime(milliSecondsToCount); } </script>
Note that, we only need to modify in html section and display method section to make the counter to display other parameters like hours, days and so on.
Write to me if you need any help!