Is there some way to make a function just like the setInterval but the timeout to be exactly the same each time. In setInterval the timeout varies about the given timeout, a little bit more, a little bit less, but very rare exactly the same.
For example:
var before = new Date().getTime();
setInterval(function() {
var after = new Date().getTime();
newTab.window.location=someURL;
console.log((after - before));
before = after;
}, 50000);
prints 50000,50002, 50005, 50994, 50997, 49999, 50003, 49998 and so on. I want to be printed always 50000
Javascript is executed in one flow only, so if there is another process doing something at the same time, there's always a chance you timer function will not be executed in time.
If you really need the exact time interval you can block the execution of any other process in advance and hope for the best:
function setExactInterval(handler, time) {
var startTime = Date.now();
setTimeout(function() {
while (true) {
var currentTime = Date.now();
var diff = currentTime - startTime;
if (diff >= time) {
setExactInterval(handler, time);
return handler();
}
}
}, time - 50);
}
It still will not be exact in case the process is blocked by OS though...
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