Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Solution 2:

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


Solution 3:

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);
}

Solution 4:

High performance & Short answer:

const runEveryFullHours = (callbackFn) => {
  const Hour = 60 * 60 * 1000;
  const currentDate = new Date();
  const firstCall =  Hour - (currentDate.getMinutes() * 60 + currentDate.getSeconds()) * 1000 - currentDate.getMilliseconds();
  setTimeout(() => {
    callbackFn();
    setInterval(callbackFn, Hour);
  }, firstCall);
};

Usage:

runEveryFullHours(() => console.log('Run Every Full Hours.'));

Solution 5:

This is how I would go about it, expanding on the previous answer:

function callEveryFullHour(my_function) {

    var now = new Date();
    var nextHour = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 0, 0, 0);
    var difference = nextHour - now;

    return window.setTimeout(function(){

        // run it
        my_function();

        // schedule next run
        callEveryFullHour(my_function);

    }, difference);
}

This way you can start stop any function from running on the full hour.

Usage:

let my_function = () => { // do something };
let timeout = callEveryHour(my_function);

// my_function will trigger every hour

window.clearTimeout(timeout);

// my_function will no longer trigger on the hour

Post a Comment for "Javascript: How To Do Something Every Full Hour?"