Reputation: 1333
Let's say there is a function x()
which does some animation
If I loop through x()
, say 100 times it takes < 1ms (on average / call) to execute it
However, if I do setInterval(x, 100)
it takes on average of > 150ms to execute
Because of this quirkiness my animation is choppy.
(The reason for my for-loop test was to ensure x()
isn't the bottleneck)
Are there any techniques / patterns to ensure my timer gets fired (at low intervals) synchronously and at the given interval and not at the mercy of the browser?
Update: Why does the following gives varying results for varying intervals
http://jsfiddle.net/zQQgH/7/
Update 2: Thanks to lincolnk, I have updated the code for anyone to check it out http://jsfiddle.net/zQQgH/22/
Upvotes: 0
Views: 1279
Reputation: 14134
No, you can't control this really perfect.
The reason for this is, that JavaScript is single threaded and works together with the browsers UI in one thread. This means that if you write setInterval(fn, 30) . You request the browser to call fn every 30ms. But the browser won't do this at this exact time. The browser will instead add your request to a queue.
You can find more information about this behavior here.
But I don't think, that this is the main problem, why your animation is choppy. To get a smooth animation, you should use a timer between 16 and 35 ms. (Best animation time should be 16.6666667.)
There is also the possibility to use RequestAnimationFrame (This blog post has also some extra informations about how to use setInterval/setTimeout for animations). Paul Irish has written a simple polyfill for RequestAnimationFrame.
If you still have problems, simply post your animation script with working HTML/CSS. I can look into this.
Upvotes: 5