2015-02-05 50 views
-2

我有2个问题:Javascript ajax循环执行

1-当ajax post执行很多次时如何设置延迟?

2 - 当变量exe_counter达到0时如何运行some_multi_ajax_function()?

这里是我的代码:

for (i = 0; i < some_data_list.length; i++) { 
    exe_counter=1; 

    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; 
     }); 
} 

UPDATE

我很抱歉,我已经坏解释。 我想执行

data = some_data_list[1]; // second iteration. after that and others 
some_big_function(data); // this can't start if exe_counter != 0 

时exe_counter == 0它意味着some_multi_ajax_function()是完全做得到。

回答

0

在这里,你有答案了第一个问题:

Execute script after specific delay using JavaScript

现在的第二个问题,有几个问题与您的代码:

  • 要当调用同一个函数达到0会创建一个无限循环。
  • exe_counter最后没有更改。当你给出的例子中的第一个ajax返回时,它将被改变。
  • 你应该在循环外部设置exe_counter,并为其赋值some_data_list.length
  • 然后在some_multi_ajax_function中执行exe_counter--;
  • 那么你测试0,并呼吁要在终结调用的功能,但该功能不能some_multi_ajax_function()

所以它是这样的:

exe_counter = some_data_list.length; 
for (i = 0; i < some_data_list.length; i++) { 

    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 end_function() { 
     // whatever 
} 

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

这是未经测试的代码只是为了解释这些概念。也尽量不要使用全局变量(没有var子句的那些变量)。他们使你的代码混乱,难以维护。

0

你的问题不是很清楚,但它听起来像你想用when来管理ajax请求,而不是让它们全部嵌套。您可以使用apply方法将一组ajax promise传递到when

// this function returns a promise 
function some_multi_ajax_function(data){ 
    return $.ajax({ 
    // ... 
    }); 
} 

function getPromises() { 
    for (var i = 0; i < some_data_list.length; i++) { 
    var promises = []; 
    exe_counter = 1; 
    var data = some_data_list[i]; 

    // push all promises into an array 
    promises.push(some_multi_ajax_function(data); 
    } 
    return promises; 
} 

var exe_counter = 0; 

// use $.when to call all the promises and once they're 
// completed set exe_counter to 0, or whatever you need to do 
$.when.apply(null, getPromises()).then(function() { 
    exe_counter = 0; 
});