Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have to wait until all the animations are done and then call the other function. All jQuery objects implement the <a href="http://api.jquery.com/promise/" rel="nofollow">promise interface <em><sup>[docs]</sup></em></a> and they get resolved when any animation finished. Together with <a href="http://api.jquery.com/jQuery.when/" rel="nofollow"><code>$.when</code> <em><sup>[docs]</sup></em></a>, you can easily achieve what you want:</p> <pre><code>function tick(callback){ var p1 = $('#col1 img') .delay('1000') .animate({bottom:'-=80px'},5000,'easeInOutSine') .promise(); var p2 = $('#col2 img') .delay('1000') .animate({bottom:'+=720px'},1000,'easeInOutSine') .promise(); var p3 = $('#col3 img') .delay('1000') .animate({bottom:'+=560px'},500,'easeInOutSine') .promise(); var p4 = $('#col4 img') .delay('1000') .animate({bottom:'-=240px'},2000,'easeInOutSine') .promise(); // $.when returns a new promise which is resolved once each passed promise // is successfully resolved $.when(p1, p2, p3, p4).done(callback); } function tock(){ // same as the original code } tick(tock); </code></pre> <p>More information about promises / deferreds: <a href="http://api.jquery.com/category/deferred-object/" rel="nofollow">http://api.jquery.com/category/deferred-object/</a>.</p> <hr> <p>Since so much code repetition makes me anxious, here is a refactored version of the <code>tick</code> function:</p> <pre><code>function tick(callback) { var data = [ {props: {bottom: '-=80px'}, duration: 5000}, {props: {bottom: '+=720px'}, duration: 1000}, {props: {bottom: '+=560px'}, duration: 500}, {props: {bottom: '-=240px'}, duration: 2000} ]; var promises = []; // assuming the elements are in the correct document order $('#col1, #col2, #col3, #col4').find('img').each(function(i) { var d = data[i]; promises.push( $(this).delay(1000).animate(d.props, d.duration, 'easeInOutSine').promise() ); }); $.when.apply($, promises).done(callback); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload