在迭代之间的jQuery每个循环中等待/暂停/休眠 [英] Wait/Pause/Sleep in jQuery Each Loop between Iterations

查看:392
本文介绍了在迭代之间的jQuery每个循环中等待/暂停/休眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想在每次循环jQuery的每次迭代后添加一个暂停,我似乎无法弄明白。

I simply want to add a pause after each iteration of a jQuery each loop, I can't seem to figure it out.

$(".item").each(function(i){
    var el = this;
    var timer = setTimeout(function(){
        $(el).trigger("click");
    }, 500);
});

这不是每1/2秒触发一次,而是一次触发点击所有项目。

This is not firing every 1/2 second, but rather triggering click on all items at once.

我想要这样的东西(伪代码):

I want something like this (pseudocode):

$(".item").each(function(i){
    $(this).trigger("click");
    wait(500); // wait a half second before the next iteration
});

这有什么工作方法吗?

推荐答案

你不能用 $。每个真正做到这一点。您可以使用 setTimeout 并保留对您当前所在索引的引用:

You cannot really do this with $.each. You can use setTimeout and keep a reference to the index you are currently at:

function process(elements, cb, timeout) {
    var i = 0;
    var l = elements.length;

    (function fn() {
        cb.call(elements[i++]);
        if (i < l) {
            setTimeout(fn, timeout);
        }
    }());
}

process($('.item'), function() {
    $(this).click();
}, 500);

这篇关于在迭代之间的jQuery每个循环中等待/暂停/休眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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