当前位置: 动力学知识库 > 问答 > 编程问答 >

html - Time Based Polling in JavaScript

问题描述:

I am using the Date() object to make a alarm.I am trying to make an alarm clock. I want a function to execute when the time from the date object reaches the time that the user sets

The user sets the alarm by selecting a specific time. Where I am stuck is that I want to poll until the user selected time equals the system time. I tried using setTimeout() but getting 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;

}

so that's where I am getting my alarm time. So what do I use to check if this time equals the System Time (which I obtained using 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);

P.S: I took care of data mismatch, converted the time into a number. And also converted everything to normal time instead of Military time.

网友答案:
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);

You can use setInterval and keep checking to see if the time matches after you select the alarm time. After the times matche, you can trigger your function. Also have it clearInterval after the trigger.

分享给朋友:
您可能感兴趣的文章:
随机阅读: