JavaScript Counter (JavaScript Timer)

Demo
Input Time(hh:mm:ss)
Timer ::


Code
<script src="http://code.jquery.com/jquery-1.7.1.min.js"  ></script>

<script type="text/javascript">
function init()
{
var x=($("#time").val()).split(":");
timer.init(x[0],x[1],x[2]);
}
var timer = {
    minutes :0,
    seconds : 0,
    elm :null,
    samay : null,
    sep : ':',
    init : function(h,m,s)
    {
h = parseInt(h,10);
        m = parseInt(m,10);
        s = parseInt(s,10);
        if(h < 0 || m < 0 || s <0 || isNaN(h) || isNaN(m) || isNaN(s)) { alert('Invalid Values'); return; }
        this.hours = h;
this.minutes = m;
        this.seconds = s;
        timer.start();
    },
    start : function()
    {
        this.samay = setInterval((this.doCountDown),1000);
    },
    doCountDown : function()
    {
        if(timer.seconds == 0)
        {
            if(timer.minutes == 0)
            {
   if(timer.hours == 0)
   {
       clearInterval(timer.samay);
       timerComplete();
       return;
   }
   else
   {
       timer.seconds=60;
timer.minutes=59;
       timer.hours--;
   }
   }
            else
            {
                timer.seconds=60;
                timer.minutes--;
            }
        }
        timer.seconds--;
        timer.updateTimer(timer.hours,timer.minutes,timer.seconds);
    },
    updateTimer :  function(hr,min,secs)
    {
hr = (hr < 10 ? '0'+hr : hr);
        min = (min < 10 ? '0'+min : min);
        secs = (secs < 10 ? '0'+secs : secs);
if(hr<=0&&min<=0&&secs<=0)
{
document.getElementById('hours').style.display="none";
document.getElementById('minutes').style.display="none";
document.getElementById('seconds').style.display="none";
return;
    }
    else {
document.getElementById('hours').innerHTML=hr ;
document.getElementById('minutes').innerHTML=min ;
document.getElementById('seconds').innerHTML=secs;
    }
}
}
function timerComplete()
{
    alert('time out buddy!!!');
}
</script>
Input Time(hh:mm:ss)<input type="text" id="time" value="1:1:00"/><button onclick="init();">Start</button>
<div  style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:18px; color:#2A1F55" >Timer <span id="hours"></span>:<span id="minutes"></span>:<span id="seconds"></span></div>

This entry was posted in , , , , . Bookmark the permalink.

Leave a reply