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



我有以下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?
});

你需要放弃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();
}

由于 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();
}

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

只需为自己构建一个快速迭代器对象,以便轻松处理数组。

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 指出的那样,只有警报/确认才能停止循环,因为它们是 javascript 用户操作,因此迭代您自己的方式是唯一的方法。

最新更新