JavaScript: How to do something every full hour?

matlos picture matlos · Sep 7, 2012 · Viewed 22.6k times · Source

I want to execute some JS code every hour. But I can't use

setInterval("javascript function",60*60*1000);

because I want to do it every full hour, I mean in 1:00, in 2:00, in 3:00 and so on. I am thinking about something like

var d;
while(true) {
  d = new Date();
  if ((d.getMinutes() == '00') && (d.getSeconds() == '00')){
    // my code here
  }  
}

but it's too slow and it doesn't work well.

Thak you for any ideas

Answer

Heretic Monkey picture Heretic Monkey · Sep 7, 2012

I would find out what time it is now, figure out how long it is until the next full hour, then wait that long. So,

function doSomething() {
    var d = new Date(),
        h = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() + 1, 0, 0, 0),
        e = h - d;
    if (e > 100) { // some arbitrary time period
        window.setTimeout(doSomething, e);
    }
    // your code
}

The check for e > 100 is just to make sure you don't do setTimeout on something like 5 ms and get in a crazy loop.