I am trying to build a countdown that switches between play time and work time. It starts with 10 seconds of work then when it reaches 0 seconds we clear the interval and set it to 'play' and call the function again...
var model = {
intervalID: 0,
status: 'work',
workSeconds: 10,
playSeconds: 10,
}
function startCountdown(){
if (model.status === 'work') {
model.countdown = model.workSeconds;
model.intervalID = setInterval(function(){
model.countdown--;
if (model.countdown > 0) {
console.log('work', model.countdown);
} else {
model.status = 'play';
clearInterval(model.indervalId);
startCountdown();
}
}, 1000);
} else if (model.status === 'play') {
model.countdown = model.playSeconds;
model.intervalID = setInterval(function(){
model.countdown--;
if (model.countdown > 0) {
console.log('play', model.countdown);
} else {
model.status = 'work';
clearInterval(model.indervalId);
startCountdown();
}
}, 1000);
}
}
startCountdown();
This function is supposed to console log a 10 second countdown for work, then when the countdown reaches 0 switch to a 10 seconds countdown of play, and keep doing that.
At the moment it looks like no intervals are being cleared and both intervals just keep setting each other in a feedback loop.
Why are the intervals not being cleared?
I think you have a typo.
clearInterval(model.indervalId);
should beclearInterval(model.intervalID);
.I'd use
setTimeout
for this too, but I guess you already know about that.