I have 2 elements with class wave-bar
. (Actually more but for the sake of the example let's say 2)
The code below changes the height of the elements to random values (to create a waveform (think audio player) effect).
The code currently changes the height 10000 times for the first element and when that is finished it goes on and changes the second element's height.
开发者_JS百科However I would like both elements to get random heights at the same time. So that the animation of the second element doesn't wait for the first one to finish.
$('.wave-bar').each(function() {
var bar = $(this);
for (var i=0;i<=10000;i++) {
window.setTimeout(function() {
var rand_no = Math.floor(Math.random()*19);
bar.height(rand_no);
bar.css('margin-top', (18-rand_no)+'px');
}, 500);
}
});
How to set this up?
I'd create a simple jQuery plugin and apply it to each element something like this:
$.fn.pulseRandom = function () {
var repulse = function ( $elem ) {
var rand = Math.floor( Math.random() * 100 ),
time = Math.floor( Math.random() * 250 ) + 250;
$elem.animate({ height: rand, 'margin-top': 100 - rand }, time - 1);
setTimeout(function(){ repulse( $elem ); }, time);
};
repulse( this );
};
$('.wave-bar').each(function(i,ele){
$(ele).pulseRandom();
});
I also randomized the timing a bit to make it look a little more organic.
See example →
Adding another setTimeout. Like this:
$('.wave-bar').each(function() {
var bar = $(this);
setTimeout(function(){ //Added this setTimeout
for (var i=0;i<=10000;i++) {
window.setTimeout(function() {
var rand_no = Math.floor(Math.random()*19);
bar.height(rand_no);
bar.css('margin-top', (18-rand_no)+'px');
}, 500);
}
},0);
});
This will create separate "threads" for each element, so they will animate at the same time.
Cheers
PS:I you're using jquery, you should check the .animate()
method, it's very cool and easy to use.
精彩评论