Skip to content Skip to sidebar Skip to footer

Creating A Stopwatch From Scratch In JavaScript

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;

Solution 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/


Post a Comment for "Creating A Stopwatch From Scratch In JavaScript"