I'm trying to repeat a countdown pattern 4 times using a while loop but it's not cooperating.
Basically, I want it to first start count downing from 5 seconds, and then from 10 seconds and I want this to repeat 4 times.
The code worked, but once I put it in a while loop or any loop for that matter, it skips like 4 seconds and it doesn't repeat.
I also tried a do while and a for loop but they didn't change anything, it still didn't loop 4 times.
Any help is much appreciated.
Relevant JS Code:
function startCountDown() {
let reps = 1
while (reps <= 4) {
setInterval(studyCountDown, 1000);
reps++
}
}
function studyCountDown() {
const minutes = Math.floor(studyTime / 60)
let seconds = studyTime % 60
if (seconds >= 0) {
seconds = seconds < 10 ? '0' + seconds : seconds;
countdownOutput.innerHTML = `${minutes}:${seconds}`
studyTime--;
}
else {
breakCountDown()
}
}
Your setInterval in loop executes asynchronously but the good thing is, it works, just not as expected. I would recommend you to rather have a global variable tracking your loop inside setInterval which executes your function to handle the countdown.
I've modified your logic a bit just as I found mine work good for this demo snippet.
var loop = 1
var seconds = 5
var counter = 1
var interval = null
function startCountDown() {
document.getElementById("attempts").innerHTML = `Attempt: ${loop}`
interval = setInterval(studyCountDown, 1000);
}
function studyCountDown() {
if (counter <= 5) {
document.getElementById('counter').innerHTML = `${counter}`
counter++;
} else {
loop++;
if (loop > 4) {
document.getElementById("attempts").innerHTML = `Done`
document.getElementById('counter').innerHTML = ``
clearLoop();
} else {
seconds = 5;
counter = 1;
document.getElementById("attempts").innerHTML = `Attempt: ${loop}`
document.getElementById('counter').innerHTML = ``
}
}
}
function clearLoop() {
clearInterval(interval);
}
<button type="button" onclick="startCountDown()">Click Me!</button>
<p id="attempts"></p>
<p id="counter"></p>
</body>
</html>