Search code examples
javascriptperformancetimerresetstopwatch

Javascript - Basic stopwatch can be started multiple times, increasing the watch speed. Solutions?


Here is our JS code(which was basically copy pasted from elsewhere), it works, more or less, but we have a problem where if a user clicks the "start" button mutiple times the speed of the watch will increase with each button press.

var h1 = document.getElementsByTagName('h1')[0],
    start = document.getElementById('start'),
    stop = document.getElementById('stop'),
    clear = document.getElementById('clear'),
    seconds = 0, minutes = 0,
    t;

function add() {
    seconds++;
    if (seconds >= 60) {
        seconds = 0;
        minutes++;
    }
    h1.textContent = (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);

    timer();
}

function timer() {
    t = setTimeout(add, 997.5);
}


/* Start button */
document.getElementById("start").onclick = timer;

/* Stop button */
document.getElementById("stop").onclick = function () {
    clearTimeout(t);
}

/* Clear button */
document.getElementById("clear").onclick = function () {
    h1.textContent = "00:00";
    seconds = 0; minutes = 0;
    clearTimeout(t);
}

So yeah, any input would be great. I tried making the stop function("clearTimeout(t)") start with the timer function, just to see if that would reset it before it started, but it didn't work.

Any ideas? You can probably tell I'm new to this.


Solution

  • My suggestion would be to check whether the stop watch is started on each start. Either cancel the current one, and start a new one:

    function timer() {
        if (t) {
            clearTimeout(t);
        }
        t = setTimeout(add, 997.5);
    }
    

    Or do nothing if it's already started:

    function timer() {
        if (!t) {
            t = setTimeout(add, 997.5);
        }
    }
    
    document.getElementById("stop").onclick = function () {
        clearTimeout(t);
        t = null;
    }