How to call a function every hour?

后端 未结 5 1019
轻奢々
轻奢々 2021-02-07 09:30

I am trying to update information from a weather service on my page. The info should be updated every hour on the hour. How exactly do I go about calling a function on the hour

5条回答
  •  鱼传尺愫
    2021-02-07 09:57

    What you probably want is something like that:

    var now = new Date();
    var delay = 60 * 60 * 1000; // 1 hour in msec
    var start = delay - (now.getMinutes() * 60 + now.getSeconds()) * 1000 + now.getMilliseconds();
    
    setTimeout(function doSomething() {
       // do the operation
       // ... your code here...
    
       // schedule the next tick
       setTimeout(doSomething, delay);
    }, start);
    

    So basically the first time the user get the access, you need to know what is the delay in millisecond to the next "hour". So, if the user access to the page at 8:54 (with 56 seconds and 123 milliseconds), you have to schedule the first execution after around 3 minutes: after the first one is done, you can call it every "hour" (60 * 60 * 1000).

提交回复
热议问题