jackreichert
jackreichert

Reputation: 1979

Jquery Queue() Each() with Delay()

I have an array: result[i]. I'd like to loop through each field in the array and append it to an element in my page.

$("tr:first").after(result[i]);

But I'd like this to happen with a delay.

Been trying to grock how queues work with each loops and a delay, but I just can't seem to work it out. I can get a delay, but only before they're all appended.

Thanks in advance.

Upvotes: 4

Views: 7785

Answers (4)

Felix Kling
Felix Kling

Reputation: 816820

Try queue:

$.each(result, function(idx, val) {
    $("tr:first").delay(1000).queue(function(next) {
        $(this).after(val);
        next();
    });
});

Just to be complete, this is for jQuery 1.4. In earlier versions, the callback should look like:

function() {
    // do whatever here
    $(this).dequeue();
}

Upvotes: 7

Kyle Humfeld
Kyle Humfeld

Reputation: 1907

Another way you could handle this is by looping over your result array and setting up a bunch of setInterval or .delay() function calls, with delays that vary based upon the array index. For example:

for( var i = 0; i < result.length; i++ ){
  $('tr:first').delay(i*1000).after(result[i]);
}

To be sure, this isn't as good a solution as the recursive one provided by @Victor above, but it's another approach in case you don't like recursion for whatever reason.

Upvotes: 1

Victor Nicollet
Victor Nicollet

Reputation: 24577

Behold, the power of recursion:

(function append(i) {
  if (i >= result.length) return;
  $('tr:first').after(result[i]);
  setTimeout(function(){append(i+1)},1000);
})(0);

You may add an additional setTimeout depending on whether you need the first item to appear immediately or after a delay.

Upvotes: 2

hunter
hunter

Reputation: 63542

$(result).each(function(i) {
    $("tr:first").delay(1000).after(result[i]);
});

Upvotes: 1

Related Questions