JavaScript中基于时间的轮询
我正在使用JavaScript中基于时间的轮询,javascript,html,timer,Javascript,Html,Timer,我正在使用Date()对象制作闹钟。我正在尝试制作闹钟。我希望在date对象的时间达到用户设置的时间时执行一个函数 用户通过选择特定时间来设置报警。我被卡住的地方是,我想轮询,直到用户选择的时间等于系统时间。我尝试使用setTimeout(),但获取RangeError:超出了最大调用堆栈大小 function showTime(){ var e = document.getElementById("hourSelect"); var hour =
Date()
对象制作闹钟。我正在尝试制作闹钟。我希望在date对象的时间达到用户设置的时间时执行一个函数
用户通过选择特定时间来设置报警。我被卡住的地方是,我想轮询,直到用户选择的时间等于系统时间。我尝试使用setTimeout()
,但获取RangeError:超出了最大调用堆栈大小
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()
object获得)
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);
附言:我处理了数据不匹配问题,将时间转换成一个数字,还将所有时间转换成正常时间,而不是军事时间
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。您能告诉我们在哪里执行
setTimeout
函数吗?var UST=“42”;var today=new Date();var ST=today.getMinutes();while(true){setTimeout(alarm(),5000)if(parseInt(UST)=ST){alert(“BEEEP”);break}}函数alarm(){console.log(“waitng”);}