How can I run a function at a given time and date?
Example: I have a function that needs to run on the 12th of each month at 10AM.
This page will be running 24/7, if this is important.
Obviously I'd have to compare against the current date, but I'm not sure how to check if the current date and time has been matched.
Shannon
setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.
You can use JavaScript Timing Events to call function after certain interval of time: This shows the alert box every 3 seconds: setInterval(function(){alert("Hello")},3000); You can use two method of time event in javascript.
JavaScript Date getTime() getTime() returns the number of milliseconds since January 1, 1970 00:00:00.
The setTimeout method allows us to run a function once after the interval of the time. Here we have defined a function to log something in the browser console after 2 seconds. const timerId = setTimeout(() => { console. log('Will be called after 2 seconds'); }, 2000);
It's not advised to use setInterval
because it has non-deterministic behaviour - events can be missed, or fire all at once. Time will fall out of sync, too.
The code below instead uses setTimeout
with a one minute period, where each minute the timer is resynchronised so as to fall as closely to the hh:mm:00.000s point as possible.
function surprise(cb) {
(function loop() {
var now = new Date();
if (now.getDate() === 12 && now.getHours() === 12 && now.getMinutes() === 0) {
cb();
}
now = new Date(); // allow for time passing
var delay = 60000 - (now % 60000); // exact ms to next minute interval
setTimeout(loop, delay);
})();
}
On the page where o want to do the check add this
setInterval(function () {
var date = new Date();
if (date.getDate() === 12 && date.getHours() === 10 && date.getMinutes === 0) {
alert("Surprise!!")
}
}, 1000)
FIDDLE
Update- add date.getSeconds == 0
to limit it to fire only one at 10:00:00. Thanks to comments below
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With