Lars
Lars

Reputation: 8458

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.

Upvotes: 2

Views: 1109

Answers (2)

Howard
Howard

Reputation: 39187

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.

Upvotes: 1

JaredPar
JaredPar

Reputation: 754585

The problem you're having is your recording the start as soon as the page loads instead of when the user actually clicks on the start button. To record the start when the user actually clicks on the button change your doTimer function to the folowing

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

Upvotes: 1

Related Questions