Have a look here: http://jsfiddle.net/qEATW/3/
- Even if you set an interval to be, for example, one second, it won't necessarily be one second between calls.
- For timeouts and intervals, always pass in the function, never a string:
setInterval(increaseCounter, 1000)
- There's no reason to parse values from the DOM. It's incredibly inefficient to do so. If you instead use Date differences, you can simply store one variable (start time), and get hours/mins/seconds since that time. You can update the view however often you like and it will always be accurate.
- I personally prefer "recursive" timeouts as opposed to intervals. With intervals, you'll always need to take that extra step to clear the interval when you want it to stop. You can stop a timeout loop in several different ways, and it tends to be easier to understand what's going on. Timeouts also allow us the flexibility of changing the time between calls (not that that is relevant here).
- It is considered a bad practice to bind event handlers inline (on the HTML element). If you are already using jQuery, there's really no excuse for this as jQuery makes the process so very simple.
- I got rid of the "addZero" spans that you had. I'm not sure what you were doing with them, but they weren't necessary and only served to clutter the markup.
HTML:
<div class="supportClock" style="width:150px; border-radius:20px;" align="center">
<span id="counterHour">00</span>
: <span id="counterMin">00</span>
: <span id="counterSec">00</span>
</div>
<input type="button" id="timer" class="start" value="Start Timer">
JS:
(function(){
var clock = $(".supportClock"),
hr = $("#counterHour"),
min = $("#counterMin"),
sec = $("#counterSec"),
running = false,
startTime,
timeout;
function updateClock(){
var time = (new Date()) - startTime,
hrs = Math.floor(time / 1000 / 60 / 60),
mins = Math.floor(time / 1000 / 60 - hrs * 60),
secs = Math.floor(time / 1000 - mins * 60 - hrs * 60 * 60);
hr.text(hrs > 9 ? hrs : '0' + hrs);
min.text(mins > 9 ? mins: '0' + mins);
sec.text(secs > 9 ? secs : '0' + secs);
timeout = setTimeout(updateClock, 1000/2);
}
$("#timer").click(function(){
if (!running){
running = true;
this.value = "Stop Timer";
startTime = new Date();
updateClock();
}
else{
running = false;
this.value = "Start Timer";
clearTimeout(timeout);
}
});
})();