Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

setTimeout inside $.each won't respect the timing

I want to backup, delete every item in a list, and append each one after 1 second.

I am trying like this:

var backup = $('#rGallery').html();
$('#rGallery li').remove();
console.log($(backup).filter('li').length); /* it logs like 135 */
$(backup).filter('li').each(function(){
    var the = $(this);
    var timeout = setTimeout(function(){
        console.log(the.html()); /* it logs the html, but all at the same time*/
        $('#rGallery').append('<li>'+the.html()+'</li>');

        /*return*/
    },1000);
});

Its works, items are removed and then append'ed again, problem is that they're all being appended after 1 second. Instead of each one to wait 1 second from the previous one.

What am I missing here?

Upvotes: 2

Views: 955

Answers (2)

epascarello
epascarello

Reputation: 207511

Because you are telling them all to run in one second, they are not added to some magic queue and wait in line to start counting.

$(backup).filter('li').each(function(index){  //added index here
    var the = $(this);
    var timeout = setTimeout(function(){
        console.log(the.html()); /* it logs the html, but all at the same time*/
        $('#rGallery').append('<li>'+the.html()+'</li>');

        /*return*/
    },1000*(index+1)); //multiplied it here
});

Upvotes: 6

Matt
Matt

Reputation: 75317

setTimeout isn't blocking; it schedules the timeout, then continues. Therefore the next iteration of each() happens immediately, which schedules the next element for exactly the same time (etc).

You should therefore change your code like such (one approach), which runs the function every 1000ms, adding the next element to backup.

var backup = $('#rGallery li');
var i = 0;
$('#rGallery li').remove();

var interval = setInterval(function () {
    if (i === backup.length) {
        clearInterval(interval);
    } else {
        var the = $(backup).eq(i);

        $('#rGallery').append('<li>'+the.html()+'</li>');
    }

    i++;
}, 1000);

Upvotes: 3

Related Questions