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
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.
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.
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.
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.
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.
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);
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