Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval By the minute On the minute

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

like image 371
bushman Avatar asked Apr 05 '10 17:04

bushman


People also ask

Why is setInterval not accurate?

why is setInterval inaccurate? As we know, setTimeout means to run the script after the minimum threshold (MS unit), and setInterval means to continuously execute a specified script with the minimum threshold value period. Note that I use the term minimum threshold here because it is not always accurate.

Does setInterval call immediately?

This property can be used in the callback of the setInterval() function, as it would get immediately executed once and then the actual setInterval() with this function will start after the specified delay.

Does setInterval run on a separate thread?

setInterval does nothing to try to run callback in another thread such as a worker thread. It will run its callbacks in the same thread as the caller meaning it was to wait for any currently running code to complete before it can do so.

How do you pass parameters to setInterval?

The setInterval() method can pass additional parameters to the function, as shown in the example below. setInterval(function, milliseconds, parameter1, parameter2, parameter3); The ID value returned by setInterval() is used as the parameter for the clearInterval() method.


2 Answers

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.

like image 57
Joel Avatar answered Sep 25 '22 04:09

Joel


First, let's make sure we know how much time do we have until the next minute:

var toExactMinute = 60000 - (new Date().getTime() % 60000);

Now, if you want to work with setTimeout, then

setTimeout(yourfunction, toExactMinute);

If you want to do a setInterval:

setTimeout(function() {
    setInterval(yourFunction, 60000);
    yourFunction();
}, toExactMinute);
like image 22
Lajos Arpad Avatar answered Sep 23 '22 04:09

Lajos Arpad