views:

319

answers:

3
+1  Q: 

Jquery CPU usage

I am using Jquery to make an image scroll across my page horizontally. The only problem is that it uses a serious amount of cpu usage. Up to 100% on a single core laptop in firefox. What could cause this???

Jquery

<script>
    jQuery(document).ready(function() {

    $(".speech").animate({backgroundPosition: "-6000px 0px"}, 400000, null);
    });

    </script>

CSS

.speech {
    /*position:fixed;*/
    top:0;
    left:0px;
    height:400px;
    width:100%;
    z-index:-1;
    background:url(/images/speech.png) -300px -500px repeat-x;
    margin-right: auto;
    margin-left: auto;
    position: fixed;
}

HTML

<div class="speech"></div>
A: 

Hello,

If this is a memory-cpu related issue then you can nullify the result of the jQuery function call. If your call returns a jQuery Object then after the call you can set it to null:

var tmp = $(".speech").animate({backgroundPosition: "-6000px 0px"}, 400000, null);
});
tmp = null;

Note: If this IS in ANY WAY related with the memory leak then it has to do with circular references and by setting to null you can break it.

Give it a try, i would like to know the results if you have the time to post.

andreas
That's going to do no good whatsoever. The problem described is one of CPU load during the animation. Freeing the jQuery object after the animation will not affect the process of the animation itself.
Pointy
So you can leave out any issues related with memory. I would go into the animate function implementation details and check for issues, i would also make sure that the function/method contract params are understood. If animation is important in your application i would suggest looking around for JS libraries that focus on animations. There might be a plugin or extension in jQuery that handles animation in a better way. Sorry for doing no good...sometimes we need a place to start and find our way to the target after dismissing factors one by one.
andreas
+3  A: 

It's using up CPU resources because you're asking the browser to repaint an image many times per second over a long period of time. That's not free.

Pointy
+1. no vote left.
Sepehr Lajevardi
A: 

The best way to achieve this is by using a plugin such as http://www.spritely.net/download/

nharry