0
$(document).ready(function(e) {
    $('.holder').each(function()
    {
        $(this).addClass('dummy');
        setTimeout( function () {
            $('.dummy').children('.box').slideDown('300');
        },2000);
    });
});

I have n number of <div> inside another <div class='holder'>. So I thought of adding some effects to each child <div>. But the problem is all the child <div> inside the holder is sliding down simultaneously. It seems it does not obey the setTimeout(). Why this happens?

Sarvap Praharanayuthan
  • 4,212
  • 7
  • 47
  • 72

3 Answers3

2

You need to increment the loop interval, also need to use the hodler reference inside the timeout callback

$(document).ready(function (e) {
    $('.holder').each(function (idx) {
        var $this = $(this).addClass('dummy');
        setTimeout(function () {
            $this.children('.box').slideDown('300');
        }, idx * 2000);
    });
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

The each loop is executing about instantly, and you give the same timeout to all setTimeout calls. So they're all executed 2000 ms after the (instant) loop.

A simple solution :

$(document).ready(function(e) {
    $('.holder').each(function(i){
        var $this = $(this);
        $this.addClass('dummy');
        setTimeout( function () {
            $('.box', $this).slideDown('300');
        },2000*(i+1)); // give different timeouts
    });
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Use

$(document).ready(function (e) {
    $('.holder').each(function (interval) { // interval here is index of each loop
        $(this).addClass('dummy');
        var $this = $(this);
        setTimeout(function () {
            $this.children('.box').slideDown('300');
        }, 2000 * (interval + 1));
    });
});

Explanation

1st timeOut = 2000=  2000 * (interval + 1)=  2000 * (0+ 1)=  2000 * (1)
2nd timeOut = 4000=  2000 * (interval + 1)=  2000 * (1+ 1)=  2000 * (2)
3rd timeOut = 6000=  2000 * (interval + 1)=  2000 * (2+ 1)=  2000 * (3)

and so on

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107