2017-01-25 38 views
0

我正在使用Date()对象来制作闹钟。我试图制作闹钟。当日期对象的时间到达用户设置的时间时,我想要执行一个函数。JavaScript中的基于时间轮询

用户通过选择特定时间来设置闹钟。我卡住的地方是我想要轮询直到用户选择的时间等于系统时间。我试着用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); 

PS:我照顾了数据不匹配的,转换的时间为一个号码,也转换一切。正常的时间,而不是军事的时间。

+0

你能告诉我们吗你在哪里执行'setTimeout'函数? – Trucy

+0

' \t \t \t' – CoderSenju

回答

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并保持检查,看看时间匹配您选择报警时间后,经过时代matche,你可以触发你的函数。也有它clearInterval后触发器