I have this code that is supposed act as a breathing exercise counting as follow:
8 second inhale
8 second "hold inhale"
12 second "exhale"
8 second "hold exhale"
everything is working fine except the counter will increment without resetting to 1. it should be, e. g. 1 to 8 and then 1 to 8 again and then 1 to 12 and so on.
// Function to start the timer
function startTimer() {
var timer = document.getElementById('timer');
var label = document.getElementById('label');
var count = 1;
// Interval for the timer
var interval = setInterval(function() {
// Update the timer display and label
timer.textContent = count;
if (count <= 8) {
label.textContent = 'Inhale';
} else if (count <= 16) {
label.textContent = 'Pause Inhale';
} else if (count <= 28) {
label.textContent = 'Exhale';
} else if (count <= 36) {
label.textContent = 'Pause Exhale';
}
// Increment count
count++;
// Stop the timer after reaching 8, 8, 12, 8 pattern
if (count === 45) {
clearInterval(interval);
startTimer();
}
}, 1000); // 1000 milliseconds = 1 second
}
// Start the timer initially
startTimer();
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
text-align: center;
}
h1 {
font-size: 24px;
font-weight: bold;
}
p {
font-size: 18px;
}
<h1>Special Timer</h1>
<p id="timer"></p>
<p id="label"></p>
4
Answers
You should add another variable to hold each step counter, like this.
Use different variables for the count of the current action and the length of the entire cycle.
You could use a finite-state machine (https://en.wikipedia.org/wiki/Finite-state_machine):
The code is doing exactly what you are telling it to (which is always the case of course), as there is nothing in your code telling the displayed count to reset. One way you could do implement this is to have a separate count called displayedCount that resets when the hidden count reaches specific numbers, like this: