setTimeout inside $.each()

GreenDude picture GreenDude · Aug 13, 2009 · Viewed 23.3k times · Source

ok, so I've got this code:

$(this).find('article.loading').each( function(i) {

    var el = this;
        setTimeout(function () {
        $(el).replaceWith($('#dumpster article:first'));
    }, speed);

});

I want to replace each element with another but I want a delay between each replace.

I can't figure out why this isn't working, it just replaces all of them after one timeout.

Any ideas?

Thanks.

Answer

haudoing picture haudoing · Nov 24, 2012

I just modify your code and make a little change. Just a little trick.

$(this).find('article.loading').each( function(k, v) {
    var el = this;
        setTimeout(function () {
        $(el).replaceWith($('#dumpster article:first'));
    }, k*speed);
});