$ .each()中的setTimeout [英] setTimeout inside $.each()

查看:138
本文介绍了$ .each()中的setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我得到了以下代码:

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.

有什么想法吗?

谢谢.

推荐答案

您正在遍历元素,并向具有相同配置的每个元素添加一个计时器.本质上,每个元素都会立即设置一个新计时器.在所有计时器的第一个刻度上,将更新元素.每个间隔都是相同的,因此它们似乎都在同一时间更新.

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!

这篇关于$ .each()中的setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆