Skip to content
Advertisement

Am I using clearInterval incorrectly?

I am making a stopwatch program with JavaScript and I want it to start and stop when you press the spacebar. When I press the spacebar once, the timer starts. The second time I press the spacebar, it restarts and immediately starts counting again.

document.body.onkeypress = function(key) {
    if (key.keyCode == 32) {
        if (inSession) {
            inSession = false;  
            timer = 0;
            document.getElementById("timer").innerHTML = timer;
            clearInterval(incrementTimer);
        } else {
            inSession = true;
            var incrementTimer = setInterval(increment, 1000)
        }
    }
}

^ Here is my event function. How do I change my program to make the stopwatch completely stop when you click the spacebar the second time?

Advertisement

Answer

You need var incrementTimer to be declared outside of the function, right now it gets hoisted to the top and will be undefined every time onkeypress is called.

var incrementTimer;
document.body.onkeypress = function(key) {
    if (key.keyCode == 32) {
        if (inSession) {
            inSession = false;  
            timer = 0;
            document.getElementById("timer").innerHTML = timer;
            clearInterval(incrementTimer);
        } else {
            inSession = true;
            incrementTimer = setInterval(increment, 1000)
        }
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement