2011-07-28 14 views
10

¿Es posible con javascript (las soluciones de jQuery también están bien) para activar un evento/invocar una función en ciertos momentos del día, p.Evento de incendio en un momento del día

llamada myFunctionA a las 10:00

myFunctionB llamada a las 14:00 etc ..

Gracias

Marcos

+0

Deberá el evento disparado automáticamente, o sólo a una punto de tiempo particular? – reporter

+0

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

Respuesta

16
  • obtiene la hora actual
  • ponerse en milisegundos, la diferencia horaria entre el siguiente tiempo de ejecución menos la hora actual
  • setTimeout con millisecons resultado
+2

Buena idea, aunque no toma en consideración los cambios de horario de verano (probablemente no sea un problema en este caso). –

+0

¡Mejor de lo que iba a sugerir! Buena idea – Curt

+1

El problema con esta solución es que si la computadora duerme durante el tiempo de espera la alarma se activará mucho más tarde – 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 

muestra a: http://jsfiddle.net/yhDVx/4/

+4

Esta es una solución pobre. Estás desperdiciando pruebas inútiles (¡cada segundo!?!). Simplemente calcule la diferencia de tiempo (ya lo hizo) y configure el intervalo a esa diferencia. – 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

¡perfecto! gracias – moeiscool

Cuestiones relacionadas