4

In my HTML page I have 4 list items and the following jQuery code:

$('li').hide().each(function() {
    $(this).delay(500).fadeIn(1000);
});

I assumed that the statement inside the .each() function would run for the first list item, would be completed and then run for the second list item etc.

However, all four list items fade in at exactly the same time. Does this mean that the statement runs in parallel for all of the list items?

Is there a way to get the list items to fade in one at a time?

Madeleine Smith
  • 411
  • 1
  • 6
  • 12

3 Answers3

4

Since the animations are asynchronous, the loop doesn't wait for each to complete before continuing to next iteration

The loop will complete in just a few milliseconds so each item will have same visual delay.

To increment, the easiest is to use the loop index as multiplier so effectively they will all be staggered

$('li').hide().each(function(i) {
    // "i" is array index of current instance
    // delays will thus be 0*500 ... 1*500 .... n*500
    $(this).delay(i*500).fadeIn(1000);
});
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Would `i` at first iteration would be `0` resulting in product of `0` at `i*500` instead of expected delay of `500`? – guest271314 May 15 '16 at 15:47
1

They do run sequentially, your example just gives the illusion that they are running at the same time because of your use of delay/fadeIn. What you will want to do is chain the fades on each element so that the next element will only fade once the previous one completes. You can do something like this:

    $(this).delay(500).fadeIn(1000, function () {
        // Fade the next li...
    });

Of course, this wouldn't work for your specific code sample above (you'd probably want to get rid of the .each and get each li element a different way within the complete callback function)

code4pi
  • 185
  • 1
  • 7
0

You can use .queue(), .dequeue(), .next() to call functions in sequential order

$("li").hide().queue(function() {
  $(this).delay(500).fadeIn(1000, $.proxy($.fn.dequeue, $(this).next()))
}).first().dequeue()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
</ul>
guest271314
  • 1
  • 15
  • 104
  • 177