javascript setinterval 不会以低间隔同步触发
假设有一个函数 x()
可以执行一些动画,
如果我循环 x()
,比如说 100 次,它需要 x()
。 1ms(平均/调用)执行它 但是,如果我执行 setInterval(x, 100)
,则平均需要 >执行时间为 150 毫秒
由于这种奇怪的情况,我的动画很不稳定。 (我的 for 循环测试的原因是确保 x() 不是瓶颈)
是否有任何技术/模式来确保我的计时器在给定的时间同步触发(以低间隔)间隔而不是受浏览器的摆布?
更新:为什么以下内容会针对不同的时间间隔给出不同的结果
http://jsfiddle.net/zQQgH/7/
更新2:感谢lincolnk,我已经更新了任何人都可以查看的代码 http://jsfiddle.net/zQQgH/22/
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/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,你无法控制这真正的完美。
原因是 JavaScript 是单线程的,并且在一个线程中与浏览器 UI 一起工作。这意味着如果您编写 setInterval(fn, 30) 。您请求浏览器每 30 毫秒调用一次 fn 。但浏览器不会在此时执行此操作。浏览器会将您的请求添加到队列中。
您可以在此处找到有关此行为的更多信息。
但我不认为这是主要问题,为什么你的动画不稳定。 要获得流畅的动画,您应该使用 16 到 35 毫秒之间的计时器。 (最佳动画时间应为 16.6666667。)
还可以使用 RequestAnimationFrame (这篇博文还提供了一些有关如何使用 setInterval/setTimeout 进行动画的额外信息)。 Paul Irish 为 RequestAnimationFrame 编写了一个简单的polyfill。
如果您仍然遇到问题,只需使用有效的 HTML/CSS 发布您的动画脚本即可。我可以调查一下。
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.
我建议在回调中使用
setTimeout
。I'd suggest using
setTimeout
instead in your callback.