I want to create a simple eggtimer app. I created a timer and two buttons start and pause. However, since I'm a beginnner, I cannot work them right. When I hit the start button, the clock is running but if I hit the start button again, the setInterval is triggered again (which I don't want). Therefore, I used {once : true} with the event listener. But consequently when I use the pause button, I cannot resume the clock. I know I should store the event in a boolean, but I don't know how to do it correctly. Can you help me? I know the key things is setting the variable clockIsRunning in the right way. But how?
const startingMinutes = 25; let time = startingMinutes * 60; const startBtn = document.querySelector("#start-btn"); const pauseBtn = document.querySelector("#pause-btn"); const resetBtn = document.querySelector("reset-btn"); let interval; let clockIsRunning = false; // start button startBtn.addEventListener("click", startCountdown, false); 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--; clockIsRunning = true; } function startCountdown() { if ((clockIsRunning = false)) { interval = setInterval(updateCountdown, 1000); } } // pause button pauseBtn.addEventListener("click", function() { clearInterval(interval); }); <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>Reset </button> <button id="start-btn"><i class="fas fa-play"></i></ion-icon>Start</button> <button id="pause-btn"><i class="fas fa-pause"></i></ion-icon>Pause</button> </div>
let interval = nulland do a null check in the start click handler to see if you should start it. Then you would just set interval back to null on resetif ((clockIsRunning = false)) {should beif ((!clockIsRunning)) {... I also would moveclockIsRunningintostartCountDownfunction.25:00