I'm working on developing a pomodoro timer similar to the one found on this website TomatoTimer
However, I'm uncertain if my current approach is the most effective.
This is the function I have created:
function setTimer(minutes = "25") {
let duration = minutes * 60 * 1000;
let seconds = "00";
let countdown = document.getElementById("timer");
seconds = parseInt(seconds);
minutes = parseInt(minutes);
setInterval(() => {
if (seconds === 0 && minutes > 0) {
seconds = 60;
minutes = minutes - 1;
countdown.innerText = `${minutes}:${seconds}`;
}
if (seconds != 0) {
seconds = seconds - 1;
}
if (seconds.toString().length === 1 && minutes.toString().length === 1) {
countdown.innerText = `0${minutes}:0${seconds}`;
} else if (minutes.toString().length === 1) {
countdown.innerText = `0${minutes}:${seconds}`;
} else if (seconds.toString().length === 1) {
countdown.innerText = `${minutes}:0${seconds}`;
} else {
countdown.innerText = `${minutes}:${seconds}`;
}
duration = duration - 10000;
}, 1000);
}
The reason why minutes and seconds are stored as strings is because I want the timer output in the format (01:05), and using numbers causes the "00" to be displayed as "0". The formatting aspect from the third "if" statement onwards is mainly for aesthetics and can be disregarded.
After defining this function, I attached an event listener to a button to initiate it successfully.
However, the challenge lies in halting the timer function once it's running.
My primary goal is simply to terminate the execution of the function without retaining the previous time settings. Adjusting that functionality will come later.
I've experimented with different solutions, such as utilizing the clearInterval method, but encountered difficulties when trying to call the function back through the eventListener after storing the interval in a variable.
Here are some questions I have:
- Would it be more advisable to create the interval outside the function?
- Is "setInterval" the optimal choice for this scenario?
- Can the timer be stopped using the existing function setup?
To gain a comprehensive understanding of my project and progress thus far, feel free to review all my code on codepen.