在.each枚举中插入“暂停”的最佳方法 [英] Best way to insert a 'pause' in a .each enumeration

查看:108
本文介绍了在.each枚举中插入“暂停”的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery'.each()'在一组元素上插入每个枚举的'pause'的最佳/推荐方式是什么?

What is the best/recommended manner in which to insert a 'pause' with each enumeration over a set of elements using the jQuery '.each()'?

$( '.someClass' ).each( function() {
    $( this ).trigger( 'click' ); //fire some request that appends a new div on the body 
    //wait for div to be appended to the DOM.  perhaps use the pause here
    //execute code once the div has been appended 
});


推荐答案

从技术上讲,你不能这样做在您的代码中建模,因为JavaScript是单线程的,并且通常在浏览器(或选项卡)UI线程上运行 - 任何睡眠/延迟都会阻止浏览器重绘页面,也会阻止用户与页面交互。

Technically, you can't do this as you have modeled in your code, since JavaScript is single-threaded, and usually runs on the browser (or tab) UI thread -- any sleep/delay will block the browser from redrawing the page and will also prevent user interaction with the page.

您需要安排浏览器定期调用您的代码。像这样的东西可以解决这个问题:

You need to arrange for the browser to invoke your code periodically. Something like this will do the trick:

var objects = $.makeArray($( '.someClass' ));

var callback;

callback = function() {
    var item = objects.shift();

    // Do something with item.

    if (objects.length != 0) {
        setTimeout(callback, 5000);
    }
}

setTimeout(callback, 5000);

参见一个示例

此解决方案假定您希望每个项目在最后一个项目完成处理后5秒内处理。这意味着:

This solution assumes that you want each item to be processed 5 seconds from the time that the last item finished processing. This means that:


  1. 如果您在处理每个 confirm()或其他内容时item,下一个项目将在用户关闭对话框5秒后处理。

  2. 总执行时间为(5000N + T)其中N是项目数初始列表,T是处理每个项目所需的总时间。

  1. If you do confirm() or something while processing each item, the next item will be processed 5 seconds from the time that the user closes the dialog.
  2. The total execution time will be (5000N + T) where N is the number of items in the initial list, and T is the total time it takes to process each item.






这是一个可以使用的功能,它封装了这个功能:


Here's a function you can use that encapsulates this functionality:

jQuery.eachWithDelay = function(sequence, delay, callback) {
    var objects = jQuery.makeArray(sequence);

    if (objects.length == 0) {
        return;
    }

    var f;

    f = function() {
        var item = objects.shift();

        if (callback(item) && objects.length != 0) {
            setTimeout(f, delay);
        }
    };

    setTimeout(f, delay);
};

被称为:

$.eachWithDelay($('.someClass'), 5000, function(item) {
    // Do something with item

    return true; // Return true to continue iterating, or false to stop.
});

参见更新小提琴

这篇关于在.each枚举中插入“暂停”的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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