Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout inside $.each()

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.

like image 521
GreenDude Avatar asked Aug 13 '09 09:08

GreenDude


People also ask

Does setTimeout work inside forEach?

There needs to be a delay between each time it is called. I've put it inside a setTimeout inside the forEach. It isn't respecting the timeout after the first wait. Instead it is waiting once, then running all at once.

Does setTimeout repeat?

setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

How does setTimeout work in loop?

The setTimeout function callback isn't triggered until the for loop execution has completed. When the for loop has finished executing the value of i is 5. Now when the setTimeout call begins to execute it uses the last set value of i which is 5. Hence 5 is printed in all the setTimeout callbacks.

Does setTimeout run on different thread?

This tells me that setTimeout() does not run on a separate thread. Show activity on this post. When you call setTimeout() typically control is passing back into the host environment (the browser or native node. js code for example).


1 Answers

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);
});

P.S. This solution is not the optimize solution but it help you to get job done fast. In most case it's fine. Just like jquery itself.

like image 68
haudoing Avatar answered Sep 24 '22 18:09

haudoing