Search code examples
javascriptonclickstopwatch

Javascript Stopwatch not starting at zero


I've got a basic stopwatch here, but the problem is I think it begins counting when the page loads as opposed to when the start button is clicked. Likewise, when you reset and start again the same problem happens.

<form>
    <input type="button" value="Start count!" onclick="doTimer()" />
    <input type="text" id="txt" />
    <input type="button" value="Stop count!" onclick="stopCount()" />
    <input type="button" value="Reset!" onclick="resetCount()" />
</form>

<script type="text/javascript">

var start = new Date().getTime(); 
var elapsed = '0.0'; 
var t;
var timer_is_on=0;

function timedCount() {
    var time = new Date().getTime() - start;
    elapsed = Math.floor(time / 100) / 10; 
    if(Math.round(elapsed) == elapsed) { elapsed += '.0'; } 
    document.getElementById('txt').value=elapsed;
    t=setTimeout("timedCount()",50);
}

function doTimer() {
    if (!timer_is_on) {
        timer_is_on=1;
        timedCount();
    }
}

function stopCount() {
    clearTimeout(t);
    timer_is_on=0;
}

function resetCount() {
    document.getElementById('txt').value='0.0';
    var elapsed = '0.0';
}


</script>

I've tried defining the start variable onclick of the start button but not had much success so far. Any help is much appreciated thank you.


Solution

  • You'll have to include another reset in doTimer():

    function doTimer() {
        if (!timer_is_on) {
            start = new Date().getTime(); 
            timer_is_on=1;
            timedCount();
        }
    }
    

    See the running version here.