I have a function that gets individuals from the database and then, in jquery, runs through them, animating them. The problem...which I see is quite common is the fact that javascript runs through all the items in a split second and the delay would be applied to all. I have search stackoverflow and have found some references to this, but none work with my code below. Any ideas would be greatly appreciated.
$individuals = $wpdb->get_results("SELECT * FROM wp_sisanda_individualsponsors");
?>
<script type="text/javascript">
function individual_sponsors() {
var individuals = <?php echo json_encode($individuals) ?>;
individuals.sort(function() { return 0.5 - Math.random() });
jQuery.each(individuals, function (i, elem) {
var topRand = Math.floor(Math.random()*301);
var leftRand = Math.floor(Math.random()*301);
var startLeftRand = Math.floor(Math.random()*301);
jQuery('.individuals').append('<div id="'+ elem.id + '" class="indiv" style="position: absolute; bottom: -70px; left:' + startLeftRand +'px;">' + elem.name + '</div>');
jQuery('#' + elem.id).animate({
top: -100,
left: Math.floor(Math.random()*301)
},20000 + Math.floor(Math.random()*50000));
});
}
</script>
As you can see, the items get a random horizontal starting position and ending position and a random speed, this works well, except there is still major bunching of items.
I have tried limiting the amount requested initially - randomly selecting a few and then calling the function repeatedly with a php wait in between, but this, I think, caused an ifinite loop...not sure...page wasn't loading.
I hope someone can point me in the right direction.
Ideally it would animate a few...wait...and then do some more...
Thanks in advance
A PHP wait won't help you as PHP executes on the server before anything gets sent to the client (where the JavaScript executes). If you want to animate a few, wait a bit, then animate some more, until you're done then you can use setTimeout
:
var current = 0;
function animateSome() {
// Animate a few (starting at individuals[current]) and
// update current with the array index where you stopped.
// ...
// If there's anything left to do, start a timer to animate
// the next chunk of individuals.
if(current < individuals.length)
setTimeout(animateSome, 250);
}
animateSome();