views:

80

answers:

5

To the javascript enthusiasts,

how would you program a setTimeOut (or setInterval) handle to fire by the minute on the minute. So for example, if it is the 51 second of the current time, then fire it in 9 seconds, if it is the 14th second then fire it in 46 seconds

thanks

+1  A: 
var seconds = (new Date()).getSeconds();

Use 60-seconds as the timeout time. Granted, setTimeout lets you specify milliseconds, which means you should also be checking milliseconds, but this will give you "close enough" for most applications. If anything, this should make you overshoot the minute some fraction of a second, but it's better to overshoot than undershoot. Undershooting would cause catastrophic failure with this method.

Stefan Kendall
+4  A: 
var date = new Date();

setTimeout(function() {
    setInterval(myFunction, 60000);
    myFunction();
}, (60 - date.getSeconds()) * 1000);

Obviously this isn't 100% precise, but for the majority of cases it should be sufficient.

Joel Potter
Assuming processing takes some period of time, this will get off pretty quickly if myFunction takes more than 0 time, which it will.
Stefan Kendall
You need to recompute every time.
Stefan Kendall
You don't need to recompute every time. I agree `myFunction` should be called after the interval (I edited to correct), but the delay due to `setInterval` will be minuscule.
Joel Potter
I think the setInterval in javascript will fix itself if "myFunction" takes a while to compute.
M28
@M28, Since `myFunction` is a reference, it won't need to compute until the 60 seconds runs out, at which time the next interval should be set before it computes `myfunction()`.
Joel Potter
A: 
var d = new Date();
var milisecondsUntilMinuteChanges = 60000 - d.getMilliseconds() - (1000 * d.getSeconds());
chris
+1  A: 
var nextTick = function() {
  return 60000 - (new Date().getTime() % 60000);
}, timerFunction = function() {
  // do stuff
  // do stuff
  // do stuff
  setTimeout(timerFunction, nextTick());
};
var timeout = setTimeout(timerFunction, nextTick());
Pointy
FYI modulus `%` operator can be used on Date objects directly, shortening your code to `60000 - (new Date() % 60000)`.
Crescent Fresh
wow - learn something new every day!
Pointy
precisely my reason, I asked the q? :)
bushman
A: 
function waitForNewMinute() {
    if (new Date().getSeconds()>1) {
        setTimeout(waitForNewMinute, 500);
    } else {
        setInterval(doMyThing,60000);
    } 
}

waitForNewMinute();
plodder