如何在ajax完成后执行第二次循环迭代

时间:2015-02-06 14:09:42

标签: javascript ajax for-loop delay execution

如何延迟循环直到函数“some_multi_ajax_function()”更改全局变量(exe_counter将为0)?

for (i = 0; i < some_data_list.length; i++) {
    exe_counter=1;
     if(i>0 && exe_counter != 0){
            delay{
                // delay for loop until some_multi_ajax_function() set exe_counter = 0
                // do not execute second iteration
            }
      }else{
            data = some_data_list[i];
           // Many ajax posts will be executed here. In the end exe_counter will be set to 0;
           some_multi_ajax_function(data);
      }
}

function some_multi_ajax_function(data){
    $.ajax({
            ...
      }.done(function(d) {
           // here it could be used another ajax function 
           exe_counter = 0;
      });
}

1 个答案:

答案 0 :(得分:3)

您使用错误的解决方案来解决问题。

如果您想等待Ajax操作,则必须仅使用回调。

然后递归你应该这样做:

function some_multi_ajax_function(data, i) {
    $.ajax({
        ...
    }.done(function(d) {
         if (i < data.length) {
             some_multi_ajax_function(data, i + 1);
         } else {
             // Do something in the end
         }
    });
}

some_multi_ajax_function(some_data_list, 0);