开发者

Javascript setInterval - how to set a good timing & performance

I'm writing a simple jquery plugin that let me add classes to elements at a certain scroll position. To accomplis开发者_StackOverflow社区h this, rather than binding onScroll events, I call a setInterval function that checks the current Y page offset:

interval = window.setInterval(update, 25);

How you can see, I set the interval at 25 ms. I was wondering if this is to be considered a right time, and how the performance are effectively involved.


For performance while animating, it's better to use 'requestAnimationFrame'. This way, the browser won't be updating all the time while the tab isn't active + it might do some additional optimizations.

requestAnimationFrame isn't supported yet by most browsers but - of course - Paul Irish has a nifty polyfill ready: http://paulirish.com/2011/requestanimationframe-for-smart-animating/


i think performance wise you better should be going with something like the code below, this way you are sure that the update function only gets triggered when running update function has finished.

function update() {
  //do stuff
  setTimer(); 
}

function setTimer() {
  timeout = window.setTimeout(update(), 25);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜