Reputation: 73
I found a jQuery script online that creates multiple span elements below the viewport (each containing the same small animated gif) and moves each of these to the top of the page at different speeds and then repeats the loop over and over.
Currently this uses about 10% of my processor time. Is there anyway to reduce this CPU usage even further? I have reduced the number of span elements, but this didn't help very much.
I read about setting setInterval
, which I have done and it helped somewhat, but I still believe it is too high for what I believe is a simple animation.
var easings=[]
$.each($.easing,function(i,v){
if ($.isFunction(v))
easings.push(i)
})
function randomEasing(){
return easings[Math.floor(Math.random()*easings.length)]
}
function cloud(x,y,toX,toY,speed){
var easingUp=randomEasing()
$('<span class="cloud">')
.text(easingUp)
.css({
top:y,
left:x
})
.animate({
top:toX,
left:toY
},{
duration:speed||500,
complete: function(){
$(this).remove();
cloud(x,y,toX,toY,speed)
},
specialEasing: {
top: easingUp,
height: randomEasing()
}
})
.appendTo('body')
}
function randy(from,to){
return Math.floor(Math.random()*(to-from)+from)
}
$(function(){
var bottom=$(window).height()+90
var right=$(window).width()-200
for(var left=50;left<right;left+=50){
cloud(left,bottom+90,-70,"-="+randy(-10,10),randy(10000,24000))
}
})
jQuery.fx.interval = 60;
Is there anything else I can do to reduce CPU usage, or is this the best I can do with jQuery and should be looking at other solutions?
Upvotes: 2
Views: 2113
Reputation: 7668
.width()
or .height()
and .innerWidth / .outerWidth
and height respectively, is enormous. Math.floor()
and Math.random()
If you'd like to benchmark which things will benefit the most, I recommend JSPerf.com
Test different code snippets against each other that you would be using and see what things you should change (or perhaps keep the same - some things jQuery can actually do more efficiently on some browsers).
The biggest attraction jQuery would have to this is its cross-browser compatibility thoroughness. You can do this manually as well but jQuery has been optimized over many years to handle it for you. (just not version 2.x - they threw out the support for older browsers in there).
Just gotta weigh your pros and cons really.
If you have a working version of this you should post it so we can try and diagnose/pinpoint problem code.
Upvotes: 2