Reputation: 287
I've watched many tutorials with alarm clocks and created my own but I'm still learning JS and I can't pause the sound because setInterval in the clock is running. pause() doesn't work because in a second the alarm is still going off. Can anyone help me?
let now;
let hours;
let minutes;
let seconds;
function clock() {
now = new Date();
hours = now.getHours();
minutes = now.getMinutes();
seconds = now.getSeconds();
// add zero for the values lower than 10
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
document.querySelector(".hours").innerHTML = hours;
document.querySelector(".minutes").innerHTML = minutes;
document.querySelector(".seconds").innerHTML = seconds;
console.log(`${hours}:${minutes}`);
// ##### this is the part sounds the alarm #####
if (alarmTime == `${hours}:${minutes}`) {
console.log(`Alarm ringing...`);
ringtone.play();
ringtone.loop = true;
}
}
let updateClock = setInterval(clock, 1000);
let alarmTime;
let ringtone;
ringtone = new Audio("./files/alarm.wav");
function setAlarm() {
let time = `${selectMenu[0].value}:${selectMenu[1].value}`;
alarmTime = time;
content.classList.add("disable");
setAlarmBtn.innerText = "alarm is set";
console.log(alarmTime);
}
setAlarmBtn.addEventListener("click", setAlarm);
// ##### This is one of some attempts to stop it
function stop() {
ringtone.pause();
ringtone.loop = false;
}
<button class="alarm-clock-button">set alarm</button>
<button class="alarm-off-button" onclick="stop()">alarm off</button>
I don't want to copy the whole code because it is quite bulky.
Upvotes: 0
Views: 110
Reputation: 23
If you want to disable the setInterval entirely, use clearInterval(updateClock)
, if you don't want to disable it then you can put a boolean variable isPaused
and check for it when alarmTime
is being checked, you can use isPaused = !isPaused
in your stop function to toggle it or just use false
Code Example:
let isPaused = false; //declaration
if (alarmTime == `${hours}:${minutes}` && !isPaused) { // this will replace the condition!
console.log(`Alarm ringing...`);
ringtone.play();
ringtone.loop = true;
}
function setAlarm() {
let time = `${selectMenu[0].value}:${selectMenu[1].value}`;
alarmTime = time;
content.classList.add("disable");
setAlarmBtn.innerText = "alarm is set";
console.log(alarmTime);
isPaused = false; // If it's being reset for whatever reason
}
function stop() { // this will replace your stop function
ringtone.pause();
ringtone.loop = false;
isPaused = true;
}
Upvotes: 1