Reputation: 83
I'm trying to create a pomodoro clock, and I can't figure out why the resetClock function is going everything except clearing the interval for the clock. It is resetting the number, but the clock keeps counting down. I'd imagine I'll have this issue when trying to implement the stop clock function also. Can someone help?
var minutes = 25;
var seconds = 0;
var startSound = new Audio('./sounds/startsound.mp3')
var resetSound = new Audio('./sounds/resetclocksound.mp3')
var stopSound = new Audio('./sounds/pausesound.mp3')
var alarmSound = new Audio('/sounds//haoduken.mp3')
var minutes_interval;
var seconds_interval;
function startClock() {
startSound.play();
minutes = 24;
seconds = 59;
document.getElementById('minutes').innerHTML = minutes;
document.getElementById('seconds').innerHTML = seconds;
document.getElementById('start-button').removeEventListener('click', startClock)
var minutes_interval = setInterval(minutesTimer, 60000);
var seconds_interval = setInterval(secondsTimer, 1000);
function minutesTimer() {
minutes = minutes - 1;
document.getElementById('minutes').innerHTML = minutes;
}
function secondsTimer() {
seconds = seconds - 1;
document.getElementById('seconds').innerHTML = seconds;
if (seconds <= 0) {
seconds = 60;
}
if (seconds <= 0 && minutes <= 0) {
alarmSound.play()
clearInterval(minutes_interval);
clearInterval(seconds_interval);
}
}
}
function resetClock() {
clearInterval(seconds_interval);
clearInterval(minutes_interval)
resetSound.play();
var minutes = 25;
var seconds = 0;
document.getElementById('minutes').innerHTML = minutes;
document.getElementById('seconds').innerHTML = seconds;
document.getElementById('start-button').addEventListener('click', startClock)
}
Upvotes: 1
Views: 71
Reputation: 18249
The problem is on the lines where you start the interval:
var minutes_interval = setInterval(minutesTimer, 60000);
var seconds_interval = setInterval(secondsTimer, 1000);
the problem is simply your use of the var
keyword, which creates a new local variable inside the startClock
function. It does nothing to the outer (global?) variables of the same name, because those are "shadowed" by the new local variables.
As a consequence, the clearInterval
calls inside resetClock
are referencing the outer variables, which do not hold a timer ID.
The solution is probably very simple: just remove the var
from the above two lines. You now only have one "global" minutes_interval
and seconds_interval
, which will be referenced by the clearInterval
calls. From a quick glance, it appears that this should work OK for you, and that you only ever set these intervals up once before cancelling them. But if you wanted to use this code to set up multiple intervals simultaneously you'd have to rethink your approach.
Upvotes: 3