Пожарное событие в определенное время суток - PullRequest
10 голосов
/ 28 июля 2011

Возможно ли с помощью javascript (решения jQuery тоже подойдут) запустить событие / вызвать функцию в определенное время дня, например,

вызвать myFunctionA в 10:00

вызвать myFunctionBв 14:00 и т. д.

Спасибо

Марк

Ответы [ 4 ]

18 голосов
/ 28 июля 2011
  • Получить текущее время
  • Получите в миллисекундах разницу во времени между следующим временем выполнения минус текущее время
  • Заданное время с миллисекундами результата
2 голосов
/ 03 января 2014
 /**
             * 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 голосов
/ 17 мая 2018

Я столкнулся с этой проблемой и нашел более сложное решение.Основная идея та же, что и в других ответах: используйте setTimeout() с интервалом с этого момента до желаемого момента времени.

Другие детали, используемые здесь: если момент времени в прошлом, запланируйте его длязавтра (в момент времени + 24 часа).Запускайте функцию в заданный момент времени каждый день с этого момента, используя setInterval().Примечание: DST здесь не рассматривается.

Входные параметры:
time = '16:00';
triggerThis = function() { alert('this was triggered'); };

  scheduleWarning(time, triggerThis) {

    // get hour and minute from hour:minute param received, ex.: '16:00'
    const hour = Number(time.split(':')[0]);
    const minute = Number(time.split(':')[1]);

    // create a Date object at the desired timepoint
    const startTime = new Date(); startTime.setHours(hour, minute);
    const now = new Date();

    // increase timepoint by 24 hours if in the past
    if (startTime.getTime() < now.getTime()) {
      startTime.setHours(startTime.getHours() + 24);
    }

    // get the interval in ms from now to the timepoint when to trigger the alarm
    const firstTriggerAfterMs = startTime.getTime() - now.getTime();

    // trigger the function triggerThis() at the timepoint
    // create setInterval when the timepoint is reached to trigger it every day at this timepoint
    setTimeout(function(){
      triggerThis();
      setInterval(triggerThis, 24 * 60 * 60 * 1000);
    }, firstTriggerAfterMs);

  }
0 голосов
/ 28 июля 2011

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/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...