views:

89

answers:

2

How I will do that: When seconds come 31 (example 11:57 31sec.) do somthing, every minute. Using Javasript.

Thanks in advance.

+9  A: 

Read the current time, calculate the number of seconds until the next time the seconds is ':31' then use setTimeout with the appropriate delay. You could use something like this:

var atSeconds = 31;
var secondsLeft = atSeconds - new Date().getSeconds();
if (secondsLeft <= 0) secondsLeft += 60;
setTimeout(foo, secondsLeft * 1000);

Remember to call it again in the function foo so that it repeats.

Mark Byers
Somehow I doubt you would be able to reach such precision with JavaScript.
ChaosPandion
Maybe setInterval instead, to do it every minute.
Paul D. Waite
I would have to recommend passing a string to setTimeout.
ChaosPandion
setInterval would probably also work, although I'm not sure how much accuracy setInterval guarantees if left running for a long time. If each call is a fraction of a second too late, that error could build up over time.
Mark Byers
Hmm, you are definitely right. Using this method you can correct any error over time.
ChaosPandion
Ooh, yeah good point.
Paul D. Waite
+2  A: 

Something like this will probably be as close as you can get.

function initializeInterval() {
    while (new Date().getSeconds() < 30);
    setInterval(doWork, 60000);
}

function doWork() {

}
ChaosPandion