Javascript 在jQuery和x27的每次迭代之间应用延迟;s.each()方法

Javascript 在jQuery和x27的每次迭代之间应用延迟;s.each()方法,javascript,jquery,html,Javascript,Jquery,Html,以下代码块存在一些问题: $('.merge').each(function(index) { var mergeEl = $(this); setTimeout(function() { self.mergeOne(mergeEl, self, index - (length - 1)); }, 500); }); 我试图在每次调用mergeOne之间应用.

以下代码块存在一些问题:

        $('.merge').each(function(index) {
            var mergeEl = $(this);
            setTimeout(function() {
                self.mergeOne(mergeEl, self, index - (length - 1));
            }, 500);
        });
我试图在每次调用
mergeOne
之间应用.500秒延迟,但此代码在同时调用数组中的所有元素之前仅应用.500秒延迟


如果有人能解释为什么这段代码不起作用,并且可能有一个可行的解决方案,那将是非常棒的,谢谢

这里有一个通用函数,可以用来迭代jQuery对象的集合,每次迭代之间有一个延迟:

function delayedEach($els, timeout, callback, continuous) {
    var iterator;

    iterator = function (index) {
        var cur;

        if (index >= $els.length) {
            if (!continuous) {
                return;
            }
            index = 0;
        }

        cur = $els[index];
        callback.call(cur, index, cur);

        setTimeout(function () {
            iterator(++index);
        }, timeout);
    };

    iterator(0);
}
演示:(循环一次)

演示:(连续循环)

传递给回调函数的上下文和参数应该与
.each()
的方式相同

如果您想让它成为jQuery插件,因此可以像调用
$(“选择器”).delayedEach(5000,func…
)一样调用它,那么您可以使用以下方法:

$.fn.delayedEach = function (timeout, callback, continuous) {
    var $els, iterator;

    $els = this;
    iterator = function (index) {
        var cur;

        if (index >= $els.length) {
            if (!continuous) {
                return;
            }
            index = 0;
        }

        cur = $els[index];
        callback.call(cur, index, cur);

        setTimeout(function () {
            iterator(++index);
        }, timeout);
    };

    iterator(0);
};
演示:(循环一次)

演示:(连续循环)


更新


我添加了连续循环元素的功能,作为一个额外参数。传递
true
将连续循环,而传递
false
或nothing(或falsey)只在元素上循环一次。代码和小提琴包含更改。

您将无法使用
。each()
(至少是正确的)。您最好使用一个递归函数来延迟详细答案!以符合约定(例如
setTimeout
),不是应该是回调,然后是延迟吗?@ColinDeClue我不明白你的意思-就是这样,不是吗?@ian:它在
setTimeout
中,但是你的函数被称为
delay,callback
,其中
setTimeout
被称为
callback,delay
(jQuery的大多数函数都需要延迟)@伊恩,是的,函数参数,对不起。我想对于jQuery来说,它是
必要的事情
,然后
延迟
(或总时间)然后回调。所以对于
延迟每个
,我会把
回调
(因为它不是真正的回调,更多的是
操作
)在使用
必需品时
。在任何情况下,显然这是一种偏好。回答得好。