javascript - How can I run a lot of functions in sequence? -


maybe question duplicate. found lot of similar questions, no 1 can solve problem. task:

function animate(){   $ul.each(function(){      $(this).find('li').each(function(){           //animate block           $(this).animate({top:'-100%'},100,function(){              $(this).css({top:'100%'});           });           //endblock         });      }); } 

as may know, 'animate block' functions run @ same time. want them run in sequence. how can achieve that?

i have read jquery 'deferred', 'q' relate article, still confusing.

sorry english.

---------addition------

if want run animate function several times, should do?

if want avoid jquery's awkward .queue()/.dequeue(), can build promise chain jquery collection of <li> elements.

function animate($ul) {     var p = $.when(); //resolved starter promise     $("li", $ul).each(function(i, li) {         p = p.then(function() {             return $(li).animate({ top:'-100%' }, 100, function() {                 return $(li).css({ top:'100%' });             }).promise();         });     });     return p; } 

as chain settles, animations occur in sequence.

more elegantly, can extend jquery have .reduce() method, adopted array.prototype.

jquery.fn.reduce = array.prototype.reduce; 

then, build required promise chain invoking .reduce() on jquery collection.

function animate($ul) {     return $("li", $ul).reduce(function(p, li) {//wow, jquery has .reduce() method!         return p.then(function() {             //here, perform required animation , return promise of completion.             return $(li).animate({top:'-100%'}, 100, function() {                 $(li).css({top:'100%'});             }).promise();         });     }, $.when());//resolved starter promise, ie p in first iteration of .reduce() . } 

this pattern worth learning has many applications.

in both examples, outermost return allows chain .then() wherever animate() called :

animate($("ul")).then(function() {     //do when <li> animations have completed. }); 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -