I'm using requestAnimationFrame for animatin some lines in a website. The thing is that this animation increases the use of the processor significally and the animation is not smooth.

CPU Use

Sometimes is more than 70% of CPU usage.

I don't know if is the animation or the reposition of lines

function animateline() {
  reqAnimFrame =
    window.requestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    window.oRequestAnimationFrame;

  reqAnimFrame(animateline);

  x += speed;

  if (x <= 0 || x >= 475) {
    speed = -speed;
}
  reposition();
}

The full code is here http://jsfiddle.net/a4cNp/46/

The fullscreen version of the page -> http://jsfiddle.net/a4cNp/46/show/light/

Thanks in advance.

Added a Firefox Profiler image. Maybe it is usefull to locate the problem but, I still don't know how to solve it.

Firefox Profiler

有帮助吗?

解决方案

As @GameAlchemist says, put your polyfill once near the top of your code instead of inside your animation. Your animation loop gets called many times per second, so minimize the amount of work that loop has to do.

One observation: You're doing way too many jQuery selections.

First, cache the jQuery objects you want to reposition along with their dimensions:

Do this once near the top of your code:

var $area1=$("#area1");
var $area2=$("#area2");
var $area3=$("#area3");
...
var area1Width=$area1.width();
var area1Height=$area1.height();
...

Then use those cached values on your often-called code (like reposition):

function reposition(){

    $area2.css("left", area1Width+40);

    ....
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top