开发者

Javascript Stopwatch not starting at zero

开发者 https://www.devze.com 2023-04-07 03:30 出处:网络
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 pr

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;
  开发者_如何学Python      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.


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.


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();
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号