Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to do something every full hour?

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

like image 548
matlos Avatar asked Sep 06 '12 22:09

matlos


People also ask

How do you call a function every hour?

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

How do you call a function every 24 hours?

If this is a server that's running constantly, you can just use setInterval() . setInterval(myFunction, 1000 * 60 * 60 * 24); This will call your function myFunction every 24 hours.

How do you call a function continuously in JavaScript?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.

Does JavaScript have a timer function?

There are two timer functions in JavaScript: setTimeout() and setInterval() . The following section will show you how to create timers to delay code execution as well as how to perform one or more actions repeatedly using these functions in JavaScript.


Video Answer


3 Answers

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.

like image 131
Heretic Monkey Avatar answered Oct 12 '22 13:10

Heretic Monkey


What you can do is have an interval run every minute, and check if the time is :00 before running the actual code.

like image 44
Niet the Dark Absol Avatar answered Oct 12 '22 13:10

Niet the Dark Absol


look at this one :

function to_be_executed(){
    ...
    ...
    ...
    makeInterval();
}

function makeInterval(){
    var d = new Date();
    var min = d.getMinutes();
    var sec = d.getSeconds();

    if((min == '00') && (sec == '00'))
        to_be_executed();
    else
        setTimeout(to_be_executed,(60*(60-min)+(60-sec))*1000);
}
like image 40
Rami Jarrar Avatar answered Oct 12 '22 14:10

Rami Jarrar