Am I using clearInterval incorrectly?
Solution 1:
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)
}
}
}