javascript - 在 jquery 中的特定时间间隔的每次迭代中停止 .each 执行?

标签 javascript jquery time each intervals

我正在尝试在我的 javascript 中创建以下功能:

$("mySelector").each(function(){

// Do something (e.g. change div class attribute)   
// call to MyFunction(), the iteration will stop here as long as it will take for myFunction to complete

});

function myFunction() 
{   
 // Do something for e.g. 5 seconds 
}

我的问题是如何在 myFunction() 期间停止每次迭代?

最佳答案

不,那是不可能的。您必须以不同的方式对其进行编码,可能使用基于 .each 的当前索引的 setTimeout。

$("mySelector").each(function(i){

    // Do something (e.g. change div class attribute)   
    // call to MyFunction(), the iteration will stop here as long as it will take for myFunction to complete
    setTimeout(myFunction,i*5000);

});

function myFunction() 
{   
 // Do something for e.g. 5 seconds 
}

编辑:您也可以通过排队来完成:http://jsfiddle.net/9Bm9p/6/

$(document).ready(function () {
    var divs = $(".test");
    var queue = $("<div />");

    divs.each(function(){
        var _this = this;
        queue.queue(function(next) {
            myFunction.call(_this,next); 
        });
    });
});

function myFunction(next) {    
    // do stuff
    $(this).doSomething(); 

    // simulate asynchronous event
    var self = this;
    setTimeout(function(){
        console.log(self.id);
        // go to next item in the queue
        next();
    },2000);

}

关于javascript - 在 jquery 中的特定时间间隔的每次迭代中停止 .each 执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12395774/

相关文章:

javascript - 为 Rails 设置 JavaScript 格式

javascript - 淡入淡出图像之间没有黑色传输 - JQuery

javascript - 在 React 和 jQuery 中获取鼠标坐标

android - java.text.parseException : Unparseable date : 2020-02-06T08:00:00

python - 在 Python 中调整日期时区的优雅方式

javascript - Angular 4 : How to show Re-login Dialog/Modal from intercepter

javascript - 如何调整 Invisible RECAPTCHA Image Select Pop Up Frame 的大小

javascript - 使用 jQuery 在另外两个 div 周围创建包装器 div

Golang 时间(分秒)

javascript - 打电话怎么能一直不显示手机屏幕?