I am creating a countdown timer and I managed to get the timer to display and countdown, but it starts automatically when the page loads. I would like to prevent this. I know how to add an event handler I just can't work out how to stop it loading automatically.
Edited as I forgot to copy in a a div with countdown as #id.
((d) => {
let start = d.getElementById("start");
let stop = d.getElementById("stop");
let reset = d.getElementById("reset");
let timerFormat = (s) => {
return (s - (s %= 60)) / 60 + (9 < s ? ":" : ":0") + s;
};
let counter;
let startTime = 1500;
timer = () => {
startTime--;
document.getElementById("countdown").innerHTML = timerFormat(startTime);
if (startTime === 0) clearInterval(counter);
};
counter = setInterval(timer, 1000);
startHandler = () => {
let el = document.getElementById("start");
el.addEventListener("click", counter);
};
})(document);
<div id="countdown"></div>
<button class="btn" id="start">Start</button>
<button class="btn" id="stop">Stop</button>
<button class="btn" id="reset">Reset</button>
counter = setInterval(timer, 1000);This line is starting the timer. When you callsetInterval, the interval starts immediately. You don't want to init that until the button is clicked.