Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 483
Toni Michel Caubet Avatar asked Mar 02 '26 15:03

Toni Michel Caubet


1 Answers

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
});
like image 133
epascarello Avatar answered Mar 05 '26 05:03

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!