Javascript 将闹钟时间与时钟时间进行比较


嗨,我的

HTML 标签标签中有一个输入小时时间和分钟时间来设置我的闹钟......

我想与时钟时间进行比较,看看它们是否匹配,然后发出闹钟声

我试过了

var alarmAudio = new Audio('alarm.wav');
timer();
function timer() {
    "use strict";
    const DATE = new Date();
    let monthNames = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    let dayNames = ["Monday", "Tuesday", "Wendesday", "Thursday", "Friday", "Saturday", "Sunday"];
    console.log(DATE);
    document.getElementById('year').innerHTML = DATE.getFullYear();
    document.getElementById('month').innerHTML = monthNames[DATE.getMonth()];
    document.getElementById('date').innerHTML = DATE.getDate();
    document.getElementById('day').innerHTML = dayNames[DATE.getDay() - 1];
    var hour = document.getElementById('time').innerHTML = DATE.getHours();
    var min = document.getElementById('time').innerHTML = DATE.getMinutes();
    var sec = document.getElementById('time').innerHTML = DATE.getSeconds();
    //change the vars types to string and check if it's 1 or 2 digits
    hour = hour.toString()
    if (hour.length < 2) {
        //prepend a 0 to the string to pad if necessary
        hour = '0' + hour;
    }
    min = min.toString()
    if (min.length < 2) {
        //prepend a 0 to the string to pad if necessary
        min = '0' + min;
    }
    sec = sec.toString()
    if (sec.length < 2) {
        sec = '0' + sec;
    }
    let theTime = document.getElementById('time').innerHTML = hour + " : " + min + " : " + sec;
    setTimeout(timer, 500);
}
// alarmtime and time match start Alarm
function setAlarm() {
    
}
// Loop Alarm
// Click on alarm button stop sound
// Reset 
<div id="set-alarm">
  <h2 class="set-alarm-header">Set Alarm</h2>
  <label style="display:inline-block;" class="set-hours">
    <p class="time-setting-hours">Hours</p>
    <input type="number" value="0" min="0">
  </label>
  <label style="display:inline-block;" class="set-minutes">
    <p class="time-setting-minutes">Minutes</p>
    <input type="number" value="0" min="0">
  </label>
</div>

如何将标签标签中设置的时间与时钟上的时间进行比较?

如果你使用:

let timeNow = Date.now();

。并与您的小时和分钟进行比较?

若要将系统时间与控件指定的时间进行比较,需要确定控件表示的时间,将其分析为实际的date对象,然后使用 setInterval 函数检查当前时间的alarmTime

请记住,在这种情况下,使用 setInterval 的效率低于使用 setTimeout(根本不需要比较时间,因为它将警报安排在特定时间发生),因为setInterval将使用更多的处理器周期来安排检查,然后比较时间。

示例(注释掉setTimeout功能):

(function () {
"use strict";
const alarmAudio = new Audio('alarm.wav');
const labelAlarmSetFor = document.getElementById('time');
let timeoutId = -1;
let intervalId = -1;
const padLeft = (value) => {
    while (value.length < 2) {
        value = '0' + value;
    }
    return value;
};
const checkTime = (alarmTime) => {
    const now = new Date();
    
    // log to console to show the constant comparisons. remove this line when you can see the wasted processor cycles.
    console.log('checking to see if ' + now.toUTCString() + ' is >= to ' + alarmTime.toUTCString());
    
    if (now >= alarmTime) {
        // time to sound the alarm
        // clear this interval as it's no longer needed
        clearInterval(intervalId);
        intervalId = -1;
        // sound the alarm
        soundAlarm();
    };
}; 
const setTimerAsTimeout = (offset) => {
    return setTimeout(soundAlarm, offset);
};
const setTimerAsInterval = (alarmTime) => {
    return setInterval( () => ( checkTime(alarmTime) ), 1000);
};
const logAlarmTimeToUser = (alarmDateTime) => {
    const monthNames = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    const dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    const year = alarmDateTime.getFullYear().toString();
    const month = monthNames[alarmDateTime.getMonth()];
    const weekday = dayNames[alarmDateTime.getDay()];
    const day = padLeft(alarmDateTime.getDate().toString());
    const hour = padLeft(alarmDateTime.getHours().toString());
    const minute = padLeft(alarmDateTime.getMinutes().toString());
    const second = padLeft(alarmDateTime.getSeconds().toString());
    const alarmDate = [year, month, day].join('-');
    const alarmTime = [hour, minute, second].join(':');
    console.log('Alarm will sound at ' + alarmDateTime.toUTCString());
    if (labelAlarmSetFor) {
        labelAlarmSetFor.innerText = 'Alarm set for ' + alarmTime + ' on ' + weekday + ', ' + alarmDate;
    }
};
const getAlarmTime = (ms) => {
    const offset = new Date();
    offset.setMilliseconds(offset.getMilliseconds() + ms);
    return offset;
};
const soundAlarm = () => {    // alarmtime and time match start Alarm
    console.log('play the sound');
    // call to alarmAudio.play(); // assuming that's how it works...
};
const preventPosts = (e) => {
    // prevent button clicks (et. al.) from posting.
    e.preventDefault();
    return false;
};
const stopAlarm = (e) => {
    if (timeoutId >= 0) {
        // cancel any existing alarms scheduled by timeout
        clearTimeout(timeoutId);
    }
    
    if (intervalId >= 0) {
        // cancel any existing alarms scheduled by interval
        clearInterval(intervalId);
    }
    
    if (labelAlarmSetFor) {
        labelAlarmSetFor.innerText = '';
    }
    // call to alarmAudio.stop(); // assuming that's how it works...
    
    if (e) {
        return preventPosts(e);
    }
};
const getElementArray = (selector) => {
    return Array.prototype.slice.call(document.querySelectorAll(selector));
};
const getParent = (elem, className) => {
    const invalidNodes = /html|body/g
    let parent = elem.parentNode ? elem.parentNode : null;
    
    if (parent && !invalidNodes.test(parent.tagName.toLowerCase())) {
        if (className) {
            if (!parent.classList.contains(className)) {
                parent = getParent(parent.parentNode, className)
            }
        }
    } else {
        parent = null;
    }
    
    return parent;
};
const changeHandler = (e) => {
    const isHours = getParent(e.target, 'set-hours') !== null;
    const isMinutes = getParent(e.target, 'set-minutes') !== null;
    const value = parseInt(e.target.value, 10) || 0;
    const factor = isHours ? value * 60 * 60 * 1000 : value * 60 * 1000;
    const alarmTime = getAlarmTime(factor);
    
    stopAlarm();
    
    /*
    // if setting as a timeout, which involves far less checking of the time (i.e., none... it just schedules the alarm to occur at a specific datetime).
    logAlarmTimeToUser(alarmTime);
    const now = new Date();
    const offset = alarmTime.getTime() - now.getTime();
    timeoutId = setTimerAsTimeout(offset);
    */
    
    // or, if setting as an interval to actually compare current system time with the alarm time, which is being done once every second (adjustable in the setTimerAsInterval function).
    logAlarmTimeToUser(alarmTime);
    intervalId = setTimerAsInterval(alarmTime);
};
const attachChangeHandler = () => {
    const hours = getElementArray('.set-hours > input[type="number"]');
    const minutes = getElementArray('.set-minutes > input[type="number"]');
    const inputs = hours.concat(minutes);
    if (!inputs.length) {
        setTimeout(attachChangeHandler, 50); // wait another 50ms and try again.
    } else {
        inputs.forEach( (input) => {
            input.addEventListener('change', changeHandler, false);
        });
    }
};
const attachClickHandler = () => {
    const button = document.getElementById('cancel-alarm');
    if (!button) {
        setTimeout(attachClickHandler, 50); // wait another 50ms and try again.
    } else {
        button.addEventListener('click', stopAlarm, false);
    }
};
//TODO: add function to Loop Alarm
//TODO: add function to Reset 
attachChangeHandler();
attachClickHandler();
}());
.set-hours, .set-minutes { display: inline-block; }
<div id="set-alarm">
  <h2 class="set-alarm-header">Set Alarm</h2>
  <label class="set-hours">
<p class="time-setting-hours">Hours</p>
<input type="number" value="0" min="0">
  </label>
  <label class="set-minutes">
<p class="time-setting-minutes">Minutes</p>
<input type="number" value="0" min="0">
  </label>
  <button id="cancel-alarm">Cancel Alarm</button>
</div>
<div>
  <label id="time"></label>
</div>

最新更新