jQuery:每个循环暂停直到完成

时间:2012-05-01 20:54:32

标签: javascript jquery foreach

我有以下jQuery循环,但在每个循环操作中我都有用户交互,代码应该等到用户交互完成。是否有可能暂停循环或是否有其他可能实现它?

jQuery.each([345, 897, 345 /* ... */], function(index, value) {
    // User interaction, need to wait the user finishing/answer

    // Here is a jQuery UI dialog with an input field in it
    // After the user entered their value and hit the submit button
    // which fires an own callback which could also continue the loop somehow?
});

3 个答案:

答案 0 :(得分:3)

您需要放弃each并自行处理。一种选择是这样的:

var curIndex = 0;
var ids = [345, 897, 345 /* ... */];

function doNext(){

  // check curIndex here to make sure you haven't completed the list, etc.

  var id = ids[curIndex++];

  // do stuff with this id
}

// THIS IS SOME SORT OF CODE EXECUTED WHEN THE "USER INTERACTION" FINISHES
function interactionDone(){
   doNext();
}

答案 1 :(得分:1)

由于javascript是单线程的,因此您可以在每个循环中放置的唯一用户操作可以是alertconfirm。如果那些不满足您的要求,您将需要自己处理每个循环。例如:

//assume foo = [345, 897, 345 /* ... */]
var i = 0;
function handleNextFoo() {
    i++;
    if(i < foo.length) {
        //Do something with foo[i]
        //now we wait for use action to call the callbackFromUserAction()
    }
}
function callbackFromUserAction() {
    //Handle user action
    handleNextFoo();
}

免责声明:应为您的产品处理命名约定,以使范围变量更具可用性。

答案 2 :(得分:0)

只需构建一个快速迭代器对象,这样就可以轻松处理数组。

var iterator = function(array) {
    this.array = array;
    this.len = array.length;
    this.index = 0;
    return this;
};

iterator.prototype.next = function(callback) {
    callback.call(null, this.array[this.index]);
    this.index++;
    if (this.index == this.len) this.onend.call(null, this.array);
    return this;
};

iterator.prototype.onend = function() {
    alert('done');
};

var iterate = new iterator(arr);

iterate.next(function(val) {
    console.log(val);
});

以下是演示http://jsfiddle.net/KfrVN/1/

但是,正如DMoses指出的那样,只有alert / confirm可以停止循环,因为它们是javascript用户操作,所以迭代你自己的方式是唯一的方法。