I have used jQuery .animate (Inspiration from how to get a div to randomly move around a page (using jQuery or CSS) ) to animate a number of divs.
I have always used javascript, not jQuery as a rule so am a little unsure of my footing here. Hence needing the snippet initially.
My code performs exactly as expected but it seems I have a memory leak somewhere, and over time (abut 10 minutes) the browser – (IE, chrome and FF) will accrue about 500MB RAM usage.
I cannot fathom why, as there are no queued instructions – as helped by the setTimeout – and no loading images etc.
(The IF statement is to allow me to at some other time – alter the class to my 50 ‘#z’ divs, and turn off animation.)
Anyone know about debugging these kind of issues? It crashes the browser over time so is essentially useless as a production page as is.
One more thing, FF’s online crash reports are flipping awful, there’s been no ‘dump’ after submitting, and the issue is less pronounced on chrome/IE – so no crash reports available.
Will update as soon as I get something useful.
function animateDiv() {
for (z = 0; z < 50; z++) {
var newq = makeNewPosition();
var oldq = $("#" + z).position()
var speed = calcSpeed([oldq.left], newq);
if (document.getElementById(z).class != "b") {
$("#" + z).animate({
left: newq
}, speed, function() {});
}
}
setTimeout(function() {
animateDiv();
}, 0.1);
}
function makeNewPosition() {
var w = $('#content').width() - 25;
var nw = Math.floor(Math.random() * w);
return [nw];
}
function calcSpeed(prev, next) {
var y = Math.abs(prev - next);
var greatest = y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
In
animateDiv(), you are both starting an animation and setting a timeout to start the next animation for 0.1 milliseconds from now. If your animation is longer than 0.1 milliseconds (which it probably is), then your animations will pile up infinitely, eventually killing the browser. Also,setTimeout()takes an integer number of milliseconds, not a decimal number of seconds.Since I doubt your intention is to have multiple animations on the exact same object all running at the same time, you should start the next animation for one object using the completion function of the previous animation, not using a timer. This would guarantee that they never pile up. For safety’s sake, you could also issue a
.stop(true)on the object before starting the next animation to make sure whatever came before is done/stopped before starting the next animation, again making sure they can never accumulate indefinitely.You could use something like this to fix the problem and be safe: