jQuery $.each() 中的 setTimeout
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1270874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setTimeout inside $.each()
提问by GreenDude
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.
谢谢。
回答by haudoing
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);
});
回答by Andy McCluggage
You are looping through the elements and adding a timer to each with the same configuration. Essentially a new timer is instantly set up for each element. On the first tick of all the timers the elements are updated. The interval is the same for each so they all appear to update at the same time.
您正在遍历元素并为每个元素添加一个具有相同配置的计时器。本质上,每个元素都会立即设置一个新的计时器。在所有计时器的第一个滴答声中,元素被更新。每个时间间隔都相同,因此它们似乎都在同一时间更新。
Your logic needs to be centred around the timer. Each tick of the timer needs to update the next element in the collection. You don't need an each loop, use the timer combined with an incremented index as your looping mechanism, stopping the timer once you have updated the last element.
您的逻辑需要以计时器为中心。计时器的每个滴答声都需要更新集合中的下一个元素。您不需要每个循环,将计时器与递增索引结合使用作为您的循环机制,一旦您更新了最后一个元素,就停止计时器。
var elements = $(this).find('article.loading');
var index = 0;
setTimeout(function () {
$(elements).get(index).replaceWith($('#dumpster article:first'));
index++;
}, speed);
Something like above, but remember to also stop the timer!
类似上面的东西,但记住也要停止计时器!
回答by RaYell
It's exactly how Andy McCluggage written. I think something like this could help you.
这正是安迪·麦克拉格 (Andy McCluggage) 所写的。我认为这样的事情可以帮助你。
var speed = 1000;
// init timer and stores it's identifier so it can be unset later
var timer = setInterval(replaceArticle, speed);
var articles = $('article.loading');
var length = articles.length;
var index = 0;
function replaceArticle() {
articles.eq(index).replaceWith($('#dumpster article:first'));
index++;
// remove timer after interating through all articles
if (index >= length) {
clearInterval(timer);
}
}
回答by Ionu? Staicu
Try with window.setTimeout
.
尝试使用window.setTimeout
.