Complete javascript beginner here, feel free to talk to me as though I'm five years old. I made a simple timer in html, css, and javascript and want to add a sound to it for when the timer reaches 0. I've tried multiple methods with my limited knowledge but nothings worked so far.
I don't know if I need to add or replace a piece of code, all I know is that I've spent multiple hours trying to find a solution with tutorials and guides but nothing's worked.
Here's my javascript code
this.el = {
minutes: root.querySelector(".timer__part--minutes"),
seconds: root.querySelector(".timer__part--seconds"),
control: root.querySelector(".timer__btn--control"),
reset: root.querySelector(".timer__btn--reset")
};
this.interval = null;
this.remainingSeconds = 0;
this.el.control.addEventListener("click", () => {
if (this.interval === null) {
this.start();
} else {
this.stop();
}
});
this.el.reset.addEventListener("click", () => {
const inputMinutes = prompt("Enter number of minutes:");
if (inputMinutes < 60) {
this.stop();
this.remainingSeconds = inputMinutes * 60;
this.updateInterfaceTime();
}
});
}
updateInterfaceTime() {
const minutes = Math.floor(this.remainingSeconds / 60);
const seconds = this.remainingSeconds % 60;
this.el.minutes.textContent = minutes.toString().padStart(2, "0");
this.el.seconds.textContent = seconds.toString().padStart(2, "0");
}
updateInterfaceControls() {
if (this.interval === null) {
this.el.control.innerHTML = `<span class="material-icons">play_arrow</span>`;
this.el.control.classList.add("timer__btn--start");
this.el.control.classList.remove("timer__btn--stop");
} else {
this.el.control.innerHTML = `<span class="material-icons">pause</span>`;
this.el.control.classList.add("timer__btn--stop");
this.el.control.classList.remove("timer__btn--start");
}
}
start() {
if (this.remainingSeconds === 0) return;
this.interval = setInterval(() => {
this.remainingSeconds--;
this.updateInterfaceTime();
if (this.remainingSeconds === 0) {
this.stop();
}
}, 1000);
this.updateInterfaceControls();
}
stop() {
clearInterval(this.interval);
this.interval = null;
this.updateInterfaceControls();
}
static getHTML() {
return `
<span class="timer__part timer__part--minutes">00</span>
<span class="timer__part">:</span>
<span class="timer__part timer__part--seconds">00</span>
<button type="button" class="timer__btn timer__btn--control timer__btn--start">
<span class="material-icons">play_arrow</span>
</button>
<button type="button" class="timer__btn timer__btn--reset">
<span class="material-icons">timer</span>
</button>
`;
}
}
new Timer(
document.querySelector(".timer")
);