Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 399
jackreichert Avatar asked Dec 21 '22 19:12

jackreichert


2 Answers

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();
}
like image 56
Felix Kling Avatar answered Jan 02 '23 21:01

Felix Kling


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.

like image 24
Victor Nicollet Avatar answered Jan 02 '23 19:01

Victor Nicollet