2011-07-28 35 views
10

是否可以使用javascript(jQuery解决方案也可以)在一天的特定时间触发事件/调用某个功能,例如: 10:00在一天中的某个特定时间发生火灾事件

呼叫myFunctionA

14:00 等呼叫myFunctionB ..

感谢

马克

+0

难道情况下自动发射,或者仅在特定的时间点? – reporter

+0

Duplicate:http://stackoverflow.com/questions/4455282/call-a-javascript-function-at-a-specific-time-of-day –

回答

16
  • 获取当前时间
  • 获取以毫秒为单位,下一次执行时间减去当前时间的时间差
  • 的setTimeout与结果millisecons
+2

好主意,虽然它没有考虑到夏令时的变化(在这种情况下可能不是问题)。 –

+0

比我要建议的更好!好主意 – Curt

+1

这个解决方案的问题在于,如果计算机在超时时间内睡眠,那么很快会触发警报 – Hampus

0

4html:

current date: <span id="cd"></span><br /> 
time to Alarm: <span id="al1"></span><br /> 
alarm Triggered: <span id="al1stat"> false</span><br /> 

的javascript:

var setAlarm1 = "14"; //14:00, 2:00 PM 
var int1 = setInterval(function(){ 
    var currentHour = new Date().getHours(); 
    var currentMin = new Date().getMinutes(); 
    $('#cd').html(currentHour + ":" + currentMin); 
    $('#al1').html(setAlarm1 - currentHour + " hours"); 
     if(currentHour >= setAlarm1){ 
      $('#al1stat').html(" true"); 
      clearInterval(int1); 
      //call to function to trigger : triggerFunction(); 
     } 
    },1000) //check time on 1s 

样品在:http://jsfiddle.net/yhDVx/4/

+4

这是一个糟糕的解决方案。你正在浪费无用的测试(每秒!?!)。只需计算时差(您已经做到了),并设置差异的时间间隔。 – xryl669

1
/** 
      * This Method executes a function certain time of the day 
      * @param {type} time of execution in ms 
      * @param {type} func function to execute 
      * @returns {Boolean} true if the time is valid false if not 
      */ 
      function executeAt(time, func){ 
       var currentTime = new Date().getTime(); 
       if(currentTime>time){ 
        console.error("Time is in the Past"); 
        return false; 
       } 
       setTimeout(func, time-currentTime); 
       return true; 
      } 

      $(document).ready(function() { 
       executeAt(new Date().setTime(new Date().getTime()+2000), function(){alert("IT WORKS");}); 
      }); 
+0

完美!谢谢 – moeiscool

相关问题