I am a JS novice trying to build a pomodoro clock with minimal functionality. While I have the basic countdown working, I am having difficulties implementing the 'add additional minute' functionality to the timer.
So far, I have this pasted immediately after my variables declaration:
// Add more minutes to timer
add.addEventListener("click", addMin);
function addMin() {
mins += 1;
timer.textContent = mins + ":" + "0" + currentSecs;
}
While this adds the minutes prior to countdown, it does not update the actual countdown minutes. Where have I gone wrong? A fresh pair of eyes on this issue would be greatly appreciated (and save a few kittens..)
I have added the HTML and JS code below:
var timer = document.getElementById("timer"),
button = document.getElementById("button"),
add = document.getElementById("add"),
minus = document.getElementById("minus"),
numOfPomodoros = 0;
// Variables for the Countdown to Work:
var mins = 25,
secs = mins * 60,
currentSecs = 0,
currentMins = 0,
comingOffBreak = false;
button.addEventListener("click", startCountdown);
function startCountdown() {
setTimeout(countdown, 500);
}
function countdown() {
currentMins = Math.floor(secs / 60);
currentSecs = secs % 60;
if (currentSecs <= 9) {
// Add an extra zero to the seconds in order to make it look more like a clock
currentSecs = "0" + currentSecs;
}
secs--;
timer.textContent = currentMins + ":" + currentSecs;
if (secs !== -1) {
// Continue the countdown
setTimeout(countdown, 1000);
} else {
// When countdown reaches 0...
if (!comingOffBreak) {
// If user just finished a pomodoro...
countNumOfPomodoros();
if (numOfPomodoros % 4 === 0) {
button.textContent = "Start Long Break";
resetForLongBreak();
} else {
button.textContent = "Start Short Break";
resetForShortBreak();
};
} else {
// If user just finished a break...
button.textContent = "Start Pomodoro";
resetCountdown();
};
};
}
function countNumOfPomodoros() {
// Add 1 to numOfPomodoros after each pomodoro is completed
numOfPomodoros++;
return numOfPomodoros;
}
function resetCountdown() {
// For new pomodoro
mins = 25;
secs = mins * 60;
currentSecs = 0;
currentMins = 0;
comingOffBreak = false;
}
function resetForShortBreak() {
mins = 5;
secs = mins * 60;
currentSecs = 0;
currentMins = 0;
comingOffBreak = true;
}
function resetForLongBreak() {
mins = 30;
secs = mins * 60;
currentSecs = 0;
currentMins = 0;
comingOffBreak = true;
}
<div class="container text-center">
<h1 id="title">POMODORO CLOCK</h1>
<div id="timerBox">
<span id="timer">25:00</span>
</div>
<br>
<button id="minus" class="btn btn-danger">- Minute </button>
<button id="button" class="btn btn-success">Start Pomodoro</button>
<button id="add" class="btn btn-primary">+ Minute</button>
</div>
You are updating the mins
variable in the method and the text, but not the seconds that are the variables considered in countdown method.
I would also consider to refactor it as the follows:
25 * 60 + extraMins * 60 - <current-time-in-secs> + <start-time-in-secs>