3

Here is some code that runs a function every second using setTimeout and then checks that the function wasn't called too early.

var date = Date.now(); 
var ttl=1000, 
    to = setTimeout(function loop () {
       console.log("triggered!"); 
       if (Date.now() - date < ttl) 
         console.error("Yes"); 
       date = Date.now(); 
       to = setTimeout(loop, ttl);
     }, ttl);

The console.error call should never occur. But if you are on chrome and hit Alt+Tab fast enough and enough times it will sometimes appear. I know chrome does some weird stuff with timeouts <1s when a tab looses focus but AFAIK it timeouts are only prolonged, never shortened.

EDIT: While I was writing this post I left such a loop running. When I went back at it here is what I see:

Premature timeouts

fakedrake
  • 6,528
  • 8
  • 41
  • 64
  • I guess it have something todo how Javascript handles timeouts and intervals. http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful You should check how much it is too early and than maybe add some "valid range" (about +/- 5ms) to your checks. – Brain Foo Long Dec 23 '15 at 13:53
  • While +10ms is acceptable, -10ms is not. The way I [understand](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Notes) the js scheduler will wait at **least** `timeout` ms before executing the code. Never less. – fakedrake Dec 23 '15 at 14:40
  • So maybe there is not a bug with the javascript interval but instead with Date.now() accuracy? Try this http://www.sitepoint.com/discovering-the-high-resolution-time-api/ – Brain Foo Long Dec 23 '15 at 15:34

0 Answers0