I’m working on a web art project that requires many objects to fade in and fade out at certain intervals (I was hoping to use 100 or more objects). I’ve got jQ reading an XML file containing the metadata and appending Ps to the body, which are then told to fade in and fade out based on info in the metadata. I’m using setTimeouts to accomplish this.
The piece is ending up to be very resource intensive. Within a minute or two of loading the page up, my machine starts wheezing. (Alternatively, I’m thinking that it might not be a resource issue but a graphical one.)
Does anyone have some advice for making this more resource-friendly/efficient? I appreciate any help!
Here’s the live link: http://justwhatdoyoucallthis.com/trynottogiveup/ (Beware of resource hog)
Here’s the relevant script:
$.ajax({
type: 'get',
url: 'problems.xml', /* ...which contains like 99 problems */
dataType: 'xml',
success: function(problems) {
$(document).ready(function() {
var winWidth=$(window).width();
var winHeight=$(window).height();
$(problems).find('problem').each(function() {
var probType=$(this).attr('type');
var probAppear=$(this).attr('appear');
var probName=$(this).children('name').text();
var probID=(probName.replace(/\s/g, '')).toLowerCase();
var probIntensity=($(this).children('intensity').text()+5)*10;
var probInterval=$(this).children('interval').text();
var probDuration=$(this).children('duration').text();
var ranLeft=Math.random()*winWidth-(probIntensity/2);
var ranTop=Math.random()*winHeight-(probIntensity/2);
$('body').append('<p id="'+probID+'" class="'+probType+'" style="left: '+ranLeft+'px; top: '+ranTop+'px; height: '+probIntensity+'px; width: '+probIntensity+'px;"><span>'+probName+'</span></p>');
(function showLoop() {
if(probAppear=='fade') { var fadeInDuration=1000; } else { var fadeInDuration=0; }
$('#'+probID).delay(probInterval*1000).fadeIn(fadeInDuration).delay(probDuration*1000).fadeOut(1000);
setTimeout(showLoop, 1000);
})();
});
});
}
});
Here’s an optimized version of your code, but like bvukelic said the whole concept would probably be more efficient with canvas.
The problem I see with the code anyway is that delay and fade actions are indeed called synchronously, but the timeout is executed asynchronously, meaning that after a while you have multiple streams of actions on the same object (and this up to a hundred times).
So the solution would be to append the repeated timeout as callback to the .fadeOut() action.