13

Is it possible with javascript (jQuery solutions are fine too) to fire an event/call a function at certain times of the day e.g.

call myFunctionA at 10:00

call myFunctionB at 14:00 etc..

Thanks

Mark

ca8msm
  • 1,170
  • 3
  • 15
  • 37

4 Answers4

20
  • Get current time
  • Get in milliseconds, the time difference between next execution time minus current time
  • Settimeout with result millisecons
hungryMind
  • 6,931
  • 4
  • 29
  • 45
  • 3
    Good idea, although it doesn't take into consideration daylight saving changes (probably not a problem in this case). – Jakub Konecki Jul 28 '11 at 08:27
  • 8
    The problem with this solution is that if the computer sleeps during the timeout the alarm will be triggered that much later – Hampus Jun 29 '17 at 12:48
  • To avoid the issue when resuming from sleep, have the event callback (or some kind of wrapper function for the callback) check the current time when it fires, so it can decide not to run if the difference is more than what it expects. – Pend Oct 20 '20 at 22:34
6

I ran into this problem and came up with a more elaborate solution. The basic idea is the same as in the other answers: use setTimeout() with an interval from now to the desired time point.

Other details used here: if the time point is in the past, schedule it for tomorrow (at time point + 24 hours). Trigger the function at the given time point every day from now using setInterval(). Note: DST is not considered here.

Input params:
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);

  }
MLavoie
  • 9,671
  • 41
  • 36
  • 56
Tiha
  • 598
  • 6
  • 10
3
 /**
             * 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");});
            });
Stefan Höltker
  • 311
  • 5
  • 21
-1

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

Sample at: http://jsfiddle.net/yhDVx/4/

jmav
  • 3,119
  • 4
  • 27
  • 27
  • 5
    This is a poor solution. You're wasting useless tests (every seconds!?!). Just compute the time difference (you already did it), and set the interval to that difference. – xryl669 Oct 17 '13 at 16:13