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
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 // ...
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.
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.
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.
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.
What you can do is have an interval run every minute, and check if the time is :00
before running the actual code.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With