How to run a function at a specific time and date?

How to run a function at a given time and date.

For example, I have a function that on the 12th of every month at 10 am, I have a surprise, and I want to tell them that. How can I always run this function, but only execute it at this time?

This page will work 24/7 as indicated, apparently this may affect my answer.

Obviously, I would have to compare with the current date, but I'm not sure how to check if the current date and time match.

Shannon

+4
source share
5 answers

setInterval, - . - .

setTimeout , , hh: mm: 00.000s.

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);
    })();
}
+8

, o ,

setInterval(function () {
    var date = new Date();
    if (date.getDate() === 12 && date.getHours() === 10 && date.getMinutes === 0) {
        alert("Surprise!!")
    }
}, 1000)

FIDDLE


- date.getSeconds == 0, , 10:00:00.

+3

-

var runned = false;
var d = new Date();
if(d.getDate() == 12 && d.getHours() == 10 && !runned){
    //Do some magic
    runned = true;
}

( , d.getMinutes()

+2

Date. . : (). , , . . getTime() , setTimeout .

EDIT: @Alnitak , , . setTimeout , 2147483648 .

function scheduleMessage() {
    var today=new Date()

    //compute the date you wish to show the message
    var christmas=new Date(today.getFullYear(), 11, 25)
    if (today.getMonth()==11 && today.getDate()>25)
        christmas.setFullYear(christmas.getFullYear()+1)

    var timeout = christmas.getTime()-today.getTime();
    if( timeout > 2147483647 ){
        window.setTimeout( scheduleMessage(), 2147483647 )
    } else {
        window.setTimeout(function() {alert('Ho Ho Ho!'); scheduleMessage()}, timeout)
    }
}
+1

iframe meta refresh workout

<meta http-equiv="refresh" content="{CHANGE_THIS_TO_WHAT_YOU_CALCULATED_AT_SERVER}">

javascripts setInterval

var interval = 300000; // run in 5 minutes
window.setInterval("reloadRefresh();", interval);

function reloadRefresh() {
 // do whatever
}

-3
source

All Articles