使用 clearInterval() 将"snooze"按钮添加到闹钟。我做错了什么?



我一直在做一个闹钟"应用程序"项目来练习JavaScript。我对它还很陌生,所以也许我只是没有正确理解clearInterval((,我希望有人能帮上忙。

JavaScript:

let sound = new Audio('./music/alarmsound.mp3');
let playAudio = () => sound.play();
const snooze = document.getElementById('snooze');
let pause = () => sound.pause();
let alarm = document.getElementById('alarm');
alarm.onclick = function setAlarm() {
let userHour = prompt("Please enter the hour of which you would like the alarm to be set 😄", "07");
if (userHour.charAt(0) > 0 && userHour < 10) {
userHour = "0" + userHour;
}
let userMinutes = prompt("Please enter the minutes of which you would like the alarm to be set 😄", "30");
let timeformat = [userHour, userMinutes];
function realTime() {
let realtime = new Date();
if(timeformat[0] == realtime.getHours() && timeformat[1] == realtime.getMinutes()) {
playAudio();
} 
if(timeformat[0] != realtime.getHours && timeformat[1] != realtime.getMinutes()) {
pause();
}
}
let checkTime = () => {
setInterval(realTime, 1000)
}

checkTime();
let stopAlarm = () => {
clearInterval(checkTime);
}
snooze.addEventListener("click", stopAlarm());
}

当用户点击警报按钮时,会出现一个提示,要求他们设置他们希望警报响起的小时,然后是分钟。这一部分起作用。此外,一旦一分钟过去,并且当前时间不再与用户设置的报警时间匹配,音频就会停止。然而,我正在尝试添加一个打盹按钮功能,无论我尝试什么,似乎都无法使其正常工作。

非常感谢任何提示和技巧!很抱歉,如果代码很乱,就像我说的,我刚开始使用JS。

有几件事使它无法像您预期的那样工作。查看建议的更改,我添加了评论。

const snooze = document.getElementById('snooze');
const alarm = document.getElementById('alarm');
const sound = new Audio('./music/alarmsound.mp3');
const playAudio = () => sound.play();
const pause = () => sound.pause();
let intval; // 1. keep a reference to the interval outside of setAlarm()
alarm.onclick = function setAlarm() {
let userHour = prompt("Please enter the...", "07");
if (userHour.charAt(0) > 0 && userHour < 10) {
userHour = "0" + userHour;
}
let userMinutes = prompt("Please enter the...", "30");
let timeformat = [userHour, userMinutes];
function realTime() {
let realtime = new Date();
if(timeformat[0] == realtime.getHours() && timeformat[1] == realtime.getMinutes()) {
playAudio();
} 
if(timeformat[0] != realtime.getHours && timeformat[1] != realtime.getMinutes()) {
pause();
}
}
intval = setInterval(realTime, 1000) // 2. assign interval to the variable
}
// 3. Dont set your event listener inside the setAlarm() function (unless it's required)
function stopAlarm() {
clearInterval(intval); // 4. Clear interval with correct reference
}
snooze.addEventListener("click", stopAlarm);

最新更新