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.
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With