2015-02-05 103 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; 
});