I am making a timer and for some reason the timer is not properly decrementing using the countDown function in the code below. I am using setTimeout to call it countDown repeatedly but when I checked the debugger JavaScript does not even go to that line, after the second-to-last line timeEl.textContent = tempMinutes + ":" + tempSeconds; it just stops. I tried setInterval but its the same.
I want to know how to have the timer go down and setTimeout to do its thing, but how? Any advice or help is greatly appreciated!
const workBtnEl = document.querySelector("#work-btn");
const shortBreakBtnEl = document.querySelector("#short-break-btn");
const longBreakBtnEl = document.querySelector("#long-break-btn");
let timeEl = document.querySelector("#time");
const work = 25;
const shortBreak = 5;
const longBreak = 15;
let currentMinutes, currentSeconds = 0;
workBtnEl.addEventListener("click", function() {
timeEl.textContent = "25:00";
currentMinutes = work;
countDown(currentMinutes, 0);
});
function countDown(minutes, seconds) {
if (seconds == 0) {
if (minutes == 0) {
return;
}
minutes -= 1;
seconds = 59;
}
let tempSeconds = seconds;
let tempMinutes = minutes;
if (seconds < 10) {
tempSeconds = "0" + seconds;
}
if (minutes < 10) {
tempMinutes = "0" + minutes
}
timeEl.textContent = tempMinutes + ":" + tempSeconds;
let time = setTimeout(countDown, 1000, minutes, seconds);
}
<button id="work-btn">
Work
</button>
<button id="short-break-btn">
Short break
</button>
<button id="long-break-btn">
Long break
</button>
<span id="time">Time</span>
You never decrease seconds when it is non-zero.
So add that after the if block:
if (seconds == 0) {
// your code...
} else seconds--; // <---
You need to reduce the seconds variable in the countDown function otherwise the same text will be printed to your text area each time.
Right now you just have a condition if the seconds are 0 then set seconds to 59.
See what you have done in this line :
let currentMinutes, currentSeconds = 0;
currentMinutes will be undefined mostly, I used Node REPL to check If you have something like :
let a, b = 0
The value of a was undefined & b got set to zero An appropriate assignment would be
let currentMinutes = 0;
let currentSeconds = 0;