5

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

Hristo93
  • 197
  • 12
  • 1
    No. If you want something that's accurate to thousands of a second then you're gonna need a time machine and get it from the future. The values of 50994 and 50997 I find hard to believe, but all the others are perfectly acceptable. Why don't you tell us what your problem is with the above times, so we can help with that instead? – Reinstate Monica Cellio Jul 29 '15 at 10:17
  • @Archer I believe its 50,994. – fuyushimoya Jul 29 '15 at 10:18
  • @fuyushimoya Sorry - my bad. That was a typo. I still find that one hard to believe - nearly 1 second out? – Reinstate Monica Cellio Jul 29 '15 at 10:20
  • care for millis go for rtos. browser is not right place – Dileep Jul 29 '15 at 10:20
  • 1
    If OP's running something with heavy computations or dom manipulation, its possible to delay the `interval function` as they all use same thread. And @Hristo93, I think there's no such function that can act as you expect, maybe you can find information from http://stackoverflow.com/a/985692/1737627. – fuyushimoya Jul 29 '15 at 10:21
  • Thanks guys, I was just curious – Hristo93 Jul 29 '15 at 10:31
  • 2
    Note that [the spec itself](http://www.w3.org/TR/2011/WD-html5-20110525/timers.html#dom-windowtimers-setinterval) doesn't guarantee any accuracy whatsoever - only a minimum time. Browsers can and do throttle timers, especially when things like the tab are not active etc. _"Note: This API does not guarantee that timers will fire exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected."_ – James Thorpe Jul 29 '15 at 10:41

1 Answers1

3

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

Maxim Gritsenko
  • 2,396
  • 11
  • 25