I need to start and stop a 60-second countdown by pressing the space key, all via Javascript. To do this, I thought I would have to use setInterval() and clearInterval(), however, I can't make it work. I can start the countdown, but once it has been activated I can no longer stop it. Here is my code:
var timeLeft = 60; /* countdown duration */
var isRunning = 0; /* check to see if the countdown is active or not */
document.addEventListener("keydown", function(event) { /* event listener */
if (event.keyCode == 32) { /* if the key pressed is space */
if (isRunning == 0) { /* if the counter isn't already active */
var timer = setInterval(function() { /* i'm starting the 1sec interval */
isRunning = 1; /* the countdown is switched on */
if (timeLeft <= 0) { /* if the countdown reaches zero */
clearInterval(timer); /* i'm stopping the interval */
document.getElementById("countdown").innerHTML = ":00";
} else {
document.getElementById("countdown").innerHTML = ":" + timeLeft;
timeLeft -= 1;
}
}, 1000);
}
if (isRunning == 1) { /* if the countdown is active */
isRunning = 0; /* the countdown is switched off */
clearInterval(timer); /* i'm stopping the interval */
document.getElementById("countdown").innerHTML = ":" + timeLeft;
}
}
});
What am I missing? Thank you very much for your help.
var timer
is not accessible by clearInterval(timer)
.
move var timer
to the global scope and set the interval with timer = ...
instead of var timer =...