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,
functiondoSomething() {
var d = newDate(),
h = newDate(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() + 1, 0, 0, 0),
e = h - d;
if (e > 100) { // some arbitrary time periodwindow.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 :
functionto_be_executed(){
...
...
...
makeInterval();
}
functionmakeInterval(){
var d = newDate();
var min = d.getMinutes();
var sec = d.getSeconds();
if((min == '00') && (sec == '00'))
to_be_executed();
elsesetTimeout(to_be_executed,(60*(60-min)+(60-sec))*1000);
}
Solution 4:
High performance & Short answer:
construnEveryFullHours = (callbackFn) => {
constHour = 60 * 60 * 1000;
const currentDate = newDate();
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:
functioncallEveryFullHour(my_function) {
var now = newDate();
var nextHour = newDate(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 0, 0, 0);
var difference = nextHour - now;
returnwindow.setTimeout(function(){
// run itmy_function();
// schedule next runcallEveryFullHour(my_function);
}, difference);
}
This way you can start stop any function from running on the full hour.
Usage:
letmy_function = () => { // do something };let timeout = callEveryHour(my_function);
// my_function will trigger every hourwindow.clearTimeout(timeout);
// my_function will no longer trigger on the hour
Post a Comment for "Javascript: How To Do Something Every Full Hour?"