19

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 every hour?

I kind of had an idea but I'm not sure of how to actually refine it so it works... What I had in mind was something like creating an if statement, such as: (pseudo code)

//get the mins of the current time
var mins = datetime.mins();    

if(mins == "00"){
    function();
 }

7 Answers 7

31

You want to check out setInterval: https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval

It's a little hard to tell what you're trying to call with your code, but it would be something in the form of:

function callEveryHour() {
    setInterval(yourFunction, 1000 * 60 * 60);
}

If you want it every hour, try something like:

var nextDate = new Date();
if (nextDate.getMinutes() === 0) { // You can check for seconds here too
    callEveryHour()
} else {
    nextDate.setHours(nextDate.getHours() + 1);
    nextDate.setMinutes(0);
    nextDate.setSeconds(0);// I wouldn't do milliseconds too ;)

    var difference = nextDate - new Date();
    setTimeout(callEveryHour, difference);
}

Now, this implementation checks the time once, sets the delay (or calls the function immediately), and then relies on setInterval to keep track after that. An alternative approach may be to poll the time every x many seconds/minutes, and fire it .getMinutes() == 0 instead (similar to the first part of the if-statement), which may sacrifice (marginal) performance for (marginal) accuracy. Depending on your exact needs, I would play around with both solutions.

2
  • 6
    There is a caveat here, it's not every hour, it's "wait at least and hour and call this" so it will eventually slip. Frequently that's not a problem since people don't tend to hang around on a website long enough that millisecond slippage adds up into seconds and minutes. Nov 7, 2013 at 21:54
  • The delay parameter uses milliseconds. In your case, you'll want 3600000 in that value (1 × 1000 × 60 × 60 = 3600000).
    – Joe DeRose
    Nov 7, 2013 at 21:57
13

Here is what should work (JSFiddle):

function tick() {
  //get the mins of the current time
  var mins = new Date().getMinutes();
  if (mins == "00") {
    alert('Do stuff');
  }
  console.log('Tick ' + mins);
}

setInterval(tick, 1000);

2
  • 2
    Depending on the accuracy, the OP may want to mess with the interval, either to conserve clock cycles, or ensure it occurs close to X:00:00.0000 for his purpose. One function call every second probably doesn't hurt, but if he has 53 dozen of these timer's (or the user is a power user with 40 tabs open). Nov 7, 2013 at 22:00
  • 1
    This yields 60 ALERTS over the course of the whole 00 minute! Mar 31, 2021 at 0:02
11

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).

1
  • You should re-calculate the delay every time, as you do for the initial start, to account for drift of the timer and for execution delay.
    – MikeB
    Apr 1, 2021 at 14:48
2

Repeat at specific minute past the hour

This counter is a little bit more versatile; it allows to perform a task repeatedly always at the same minute past the hour (e.g. 37 minutes past the hour), and this with up to millisecond precision.

The precision of this timer is derived from its recursion. At every recursion, the millisecond time to the next minute gets recalculated. This prevents time lag over long periods.

The % sign refers to the modulo operator.

function minuteCount(minutesAfterHour) {

    const now          = new Date();
    const hours        = now.getHours();
    const minutes      = now.getMinutes();
    const seconds      = now.getSeconds();
    const milliseconds = now.getMilliseconds();

    waitUntilNextMinute = setTimeout(minuteCount, 60000 - seconds * 1000 - milliseconds);

    if(minutes % 60 === minutesAfterHour) {
        doSomethingHourly();
    }

}

minuteCount(37);

Finally, timers are best kept away from the main thread. They are best run from within a web worker, as explained here. This works perfectly with unfocused tabs in desktop browsers.

However, dedicated web workers on Chrome for Android are put to sleep about 5 minutes after moving the main client to the background.

2
  • 1
    This is the most helpful answer! The advice to put timed functions into web workers (and a relevant, digestible linked resource) is much appreciated. Since I need this to work on Chrome for Android, I'm going to leave in in my main js file for now.
    – nanselm2
    Feb 17 at 20:26
  • FWIW, the variable "hours" isn't used. The waitUntilNextMinute variable assignment is unused as well. I simply called setTimeout() with the arguments you provided.
    – nanselm2
    Feb 17 at 20:30
0

EDIT: Oops, I didn't see the " o' clock" things, so I edit my answer :

var last_execution = new Date().getTime();
function doSomething(force){
  var current_time = new Date().getTime();
  if (force || (current_time.getMinutes() == 0)
  {
    last_execution = current_time;
    // something
    // ...
  }
  setTimeout(doSomething(false), 1000);
}
// force the first time
doSomething(true); 
3
  • That will not execute on the hour, unless the script is executed at the correct time in the first place ...
    – HaukurHaf
    Nov 7, 2013 at 21:56
  • Yes, sorry, I read that after my answer so I edited. Something like this should do the job : run it once, then every hour
    – Asenar
    Nov 7, 2013 at 22:02
  • if the user opens the page at 11:27, last execution gets set to 11:27 and hence from then on the rest of the script would execute at 27 mins past
    – OGHaza
    Nov 7, 2013 at 22:04
0
// ... call your func now
let intervalId;
let timeoutId = setTimeout(() => {
  // ... call your func on end of current hour
  intervalId = setInterval(() => {
     // ... call your func on end of each next hours
  }, 3600000);
}, ((60 − moment().minutes()) × 60 × 1000) - (moment().second() * 1000));
0

Here is my pair of setIntervalWithDelay and clearIntervalWithDelay that one can use like this:

let descriptor = setIntervalWithDelay(callback, 60 * 60 * 1000, nextHourDelay)

And when you are done with it:

clearIntervalWithDelay(descriptor)

Here is my implementation of the functions:

const setIntervalWithDelay = (callback, interval, delay = 0) => {
    let descriptor = {}
    descriptor.timeoutId = setTimeout(() => {
        if(!descriptor.timeoutId){
            return
        }
        descriptor.timeoutId = null
        callback()
        descriptor.intervalId = setInterval(callback, interval)
    }, delay)
    return descriptor
}

export const clearIntervalWithDelay = (descriptor) => {
    if(!isObject(descriptor) || (!descriptor.timeoutId && !descriptor.intervalId)){
        console.warn("clearIntervalWithDelay: Incorrect descriptor. Please pass an object returned by setIntervalWithDelay. Skipping this call.")
        return
    }
    if(descriptor.timeoutId){
        clearTimeout(descriptor.timeoutId)
        descriptor.timeoutId = null
        console.log("clearIntervalWithDelay: stopped during delay.")
    }
    if(descriptor.intervalId){
        clearInterval(descriptor.intervalId)
        descriptor.intervalId = null
        console.log("clearIntervalWithDelay: stopped during interval repeat.")
    }
}

One example of using dayjs to get the delay for the next hour:

let nextHour = dayjs().second(0).millisecond(0).add(1, "hour")
let nextHourDelay = nextHour.diff(dayjs())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.