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
ca
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);
}