Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function every hour?

Tags:

javascript

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();
 }
like image 900
user2961971 Avatar asked Nov 07 '13 21:11

user2961971


2 Answers

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.

like image 166
Igor Avatar answered Oct 11 '22 08:10

Igor


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);
like image 27
HaukurHaf Avatar answered Oct 11 '22 08:10

HaukurHaf