gpt4 book ai didi

javascript - 使用clearInterval()将 “snooze”按钮添加到闹钟。我究竟做错了什么?

转载 作者:行者123 更新时间:2023-12-03 01:21:19 29 4
gpt4 key购买 nike

我一直在研究闹钟“应用”项目,以练习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);

关于javascript - 使用clearInterval()将 “snooze”按钮添加到闹钟。我究竟做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61161466/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com