我正在使用Date()
对象发出警报。我正在尝试制作一个闹钟。我想要一个函数在日期对象的时间到达用户设置的时间
用户通过选择特定时间来设置闹钟。我被困的地方是我想要轮询,直到用户选择的时间等于系统时间。我尝试使用setTimeout()
,但获得RangeError: Maximum call stack size exceeded
function showTime(){
var e = document.getElementById("hourSelect");
var hour = e.options[e.selectedIndex].value;
var e1 = document.getElementById("autoDropDown");
var minuteSelected = e1.options[e1.selectedIndex].value;
var e2 = document.getElementById("amPmSelect");
var AMPM = e2.options[e2.selectedIndex].value;
}
这样我就可以获得闹钟时间了。那么我该怎么用来检查这个时间是否等于系统时间(我使用Date()
对象获得的。
var today = new Date();
var hours = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var suffix = (hours >= 12)? 'pm' : 'am'; //converting military time to non-military time.
hours = (hours > 12)? hours -12 : hours;
hours = (hours == '00')? 12 : hours;
m = checkTime(m);
s = checkTime(s);
P.S:我处理数据不匹配,将时间转换为数字。并且还将一切转换为正常时间而不是军事时间。
答案 0 :(得分:0)
var alarm = new Date(2017,00,25,14,9,01);
var checktime = function(){
var date = new Date();
if(alarm.getHours() === date.getHours()){
if(alarm.getMinutes() === date.getMinutes()){
if(alarm.getMinutes() === date.getMinutes()){
console.log('trigger');
return true;
}
}
return false;
};
};
var interval = setInterval(function(){
if(checktime()){
clearInterval(interval);
console.log('cleared');
};
},100);
您可以使用setInterval并在选择闹钟时间后继续检查时间是否匹配。在时间匹配之后,您可以触发您的功能。触发后也有clearInterval。