I'm trying to start a countdown function with an event listener because at the moment it starts automatically.
I found this code somewhere on the net and want to adjust it to my needs but I need some help.
I guess setInterval must be to blame. I guess it runs the function every second, right?
But I want it to start when I press the button, so I put the setInterval inside the updateCountdown body but weird things started to happen (that the clock started to work irregularly)
const startingMinutes = 25;
let time = startingMinutes * 60;
const startBtn = document.querySelector("#start-btn");
startBtn.addEventListener("click", updateCountdown);
const countdownEl = document.querySelector("#countdown");
function updateCountdown() {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 10 ? "0" + seconds : seconds;
countdownEl.innerHTML = `${minutes}:${seconds}`;
time--;
}
setInterval(updateCountdown, 1000);
<div id="display-container">
<div id="display-timer">
<p id="countdown">25:00</p>
</div>
<p id="display-logo">Focus</p>
</div>
<div id="buttons-container">
<button id="reset-btn">
<i class="fas fa-undo-alt"></i></ion-icon>
</button>
<button id="start-btn"><i class="fas fa-play"></i></ion- icon></button>
<button id="pause-btn"><i class="fas fa-pause"></i></ion-icon></button>
</div>
It sounds like you want to start the countdown only when the user clicks the button. In that case, use addEventListener to add a function that calls setInterval, passing to that the function you actually want repeated. So it will look like this:
const startingMinutes = 25;
let time = startingMinutes * 60;
const startBtn = document.querySelector("#start-btn");
startBtn.addEventListener("click", startCountdown);
const countdownEl = document.querySelector("#countdown");
function updateCountdown() {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 10 ? "0" + seconds : seconds;
countdownEl.innerHTML = `${minutes}:${seconds}`;
time--;
}
function startCountdown() {
setInterval(updateCountdown, 1000);
}
I'll leave it to you to sort out more subtle details like what should happen if the user clicks the button a second time.