In JavaScript, how can I have a function run at a specific time?

前端 未结 5 1177
感动是毒
感动是毒 2020-12-03 00:05

I have a website that hosts a dashboard: I can edit the JavaScript on the page and I currently have it refreshing every five seconds.

I am trying to now get a

5条回答
  •  渐次进展
    2020-12-03 00:19

    I have written function which

    • allows expressing delay in seconds, new Date() format and string's new Date format
    • allows cancelling timer

    Here is code:

    "use strict"
    /**
      This function postpones execution until given time.
      @delay might be number or string or `Date` object. If number, then it delay expressed in seconds; if string, then it is parsed with new Date() syntax. Example:
          scheduleAt(60, function() {console.log("executed"); }
          scheduleAt("Aug 27 2014 16:00:00", function() {console.log("executed"); }
          scheduleAt("Aug 27 2014 16:00:00 UTC", function() {console.log("executed"); }
      @code function to be executed
      @context @optional `this` in function `code` will evaluate to this object; by default it is `window` object; example:
          scheduleAt(1, function(console.log(this.a);}, {a: 42})
      @return function which can cancel timer. Example:
          var cancel=scheduleAt(60, function(console.log("executed.");});
          cancel();
          will never print to the console.
    */
    
    function scheduleAt(delay, code, context) {
    
        //create this object only once for this function
        scheduleAt.conv = scheduleAt.conv || {
            'number': function numberInSecsToUnixTs(delay) {
                return (new Date().getTime() / 1000) + delay;
            },
            'string': function dateTimeStrToUnixTs(datetime) {
                return new Date(datetime).getTime() / 1000;
            },
            'object': function dateToUnixTs(date) {
                return date.getTime() / 1000;
            }
        };
    
        var delayInSec = scheduleAt.conv[typeof delay](delay) - (new Date().getTime() / 1000);
    
        if (delayInSec < 0) throw "Cannot execute in past";
    
        if (debug) console.log('executing in', delayInSec, new Date(new Date().getTime() + delayInSec * 1000))
    
        var id = setTimeout(
            code,
            delayInSec * 1000
        );
    
        //preserve as a private function variable setTimeout's id
        return (function(id) {
            return function() {
                clearTimeout(id);
            }
        })(id);
    }
    

    Use this as follows:

    scheduleAt(2, function() {
        console.log("Hello, this function was delayed 2s.");
    });
    
    scheduleAt(
        new Date().toString().replace(/:\d{2} /, ':59 '),
        function() {
            console.log("Hello, this function was executed (almost) at the end of the minute.")
        }
    );
    
    scheduleAt(new Date(Date.UTC(2014, 9, 31)), function() {
        console.log('Saying in UTC time zone, we are just celebrating Helloween!');
    })
    

提交回复
热议问题