2017-10-20 16 views
0

您好我有我的HTML標籤,標籤,輸入小時時間,分鐘時間把我的鬧鐘......的Javascript比較alarmTime到clockTime

我要比較的時鐘時間,看看它們是否匹配,然後進行在alarmsound

我已經試過

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>

我如何比較在實驗室中設置的時間與時間在一起的時間?

+3

而問題是? – Legends

+0

'if(hour === alarmTime && min === alarmTime)'暗示'hour'和'min'是相同的,即'08:08','09:09','10:10'等。'alarmTime'神奇地代表小時值和分鐘值_simultaneously_ ...你的四個變量中的哪一個定義在哪裏?我們需要更多的JavaScript語境。 – Xufox

+0

你可能會想要setInterval()而不是一次又一次地重複設置setTimeout()https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval –

回答

0

如果你使用什麼:

let timeNow = Date.now(); 

...和比較對您小時&分鐘?

0

系統時間比較通過您的控件中指定的時間,你需要弄清楚什麼時候你的控件代表,解析到實際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>

+0

感謝您的迴應,但不是什麼我正在試圖做 –

+0

@ThomasHermansen更新了答案。 – pete