Creating a stopwatch from scratch in JavaScript

£可爱£侵袭症+ 提交于 2021-01-29 03:14:45

问题


By creating variables for milliseconds, seconds, and minutes, I wanted to make a little stopwatch project. The onClick for the button I have is for theTimer():

var milli = 0;
    var seconds = 0;
    var minutes = 0;
    var onOff = 0;

    var txtMilli = document.getElementById("txtMilli");
    var txtSeconds = document.getElementById("txtSeconds");
    var txtMinutes = document.getElementById("txtMinutes");

    function theTimer()
    {
        if (onOff == 0) {
            onOff = 1;
            timer = setInterval("startCounting()",1);
        }
        if (onOff == 1) {
            onOff == 0;
            clearInterval(timer);
        }
    }

    function startCounting()
    {
        if (milli >999) 
        { 
          milli = 0; if (seconds <60) {seconds +=1} 
        }
        else 
        {
          milli +=1;
        }
        if (seconds >59) 
        {
          seconds = 0; minutes += 1;
        }
        if (milli > 10) 
        {
          txtMilli.innerHTML = "0" + milli;
        }
        if (milli < 10) 
        {
          txtMilli.innerHTML = "" + milli;
        }
    }

Nothing shows up in the console, the problem is that the DIVs never change from 0 when running it.


回答1:


I managed to fix your code like so:

var milli = 0;
var seconds = 0;
var minutes = 0;
var onOff = 0;

var txtMilli = document.getElementById("txtMilli");
var txtSeconds = document.getElementById("txtSeconds");
var txtMinutes = document.getElementById("txtMinutes");

function startCounting(){        
    if (milli >999) { milli = 0; if (seconds <60) {seconds +=1} }
    else {milli +=1;}
    if (seconds >59) {seconds = 0; minutes += 1;}

    if (milli > 10) {txtMilli.innerHTML = "0" + milli;}
    if (milli < 10) {txtMilli.innerHTML = "" + milli;}
}

function theTimer(){
    if (onOff == 0) {
        onOff = 1;
        timer = setInterval(startCounting, 1);
    } else if (onOff == 1) {
        onOff = 0;
        clearInterval(timer);
    }
}

myButton.onclick = theTimer;

There was a bug inside theTimer where you'd set onOff to 1, then immediately check to see if it was 1 and set it back to 0. I fixed this by using else if.

I also changed onOff == 0 (which is a comparison) to onOff = 0 (which is an assignment).

Working JSFiddle: https://jsfiddle.net/k83tvfhc/



来源:https://stackoverflow.com/questions/41709953/creating-a-stopwatch-from-scratch-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!