The time delay given in setTimeout()
works differently for Windows and Ubuntu?
Why is that?
Is there a better way?
The time delay given in setTimeout()
works differently for Windows and Ubuntu?
Why is that?
Is there a better way?
The time given in setTimeout() is not guaranteed.
There are several reasons for that:
I wrote a blog post about time in JavaScript at
http://www.codebullets.com/is-time-relative-in-javascript-1365 about this topic
Better way for what?
It depends what you want to do. Also take a look at RequestAnimationFrame (http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/), maybe this is for you.
requestAnimationFrame
will trigger for each monitor VBLANK gap if requested before the next VBLANK.
That way it is a very accurate timer. However, it triggers up to 60 times per seconds and it won't be very accurate if you spend more than the 16.7ms time-budget you get before you need to call it again.
If your functions operates within this time-budget, requestAnimationFrame
will be most accurate you can get access to from Javascript.
It's triggered almost the same way as setTimeout
:
function myLoop() {
//... < 16.7ms to finish work...
requestAnimationFrame(myLoop);
}
Note: you will need to use prefixes in some browsers or a polyfill (see chris' answer for link).