2013-04-11 78 views
0

我要推迟几毫秒的请求。如何延缓for循环

我做的3 Ajax调用它的jQuery当内部为的loop.that长度环路最多20个。

意味着我做的很少seconds.In浏览器,Firefox,safary和歌剧近60个请求却没有这个问题,但在IE的中止请求。

我的For循环

for (index in personScoreCollection.collection) { 
     //Get the 4th and 5th score simultaniously. 
     $.when(UserSearch(index), UsabilityScore(index), UserConnection(index)).done(); 
    } 

所有具有一个一个Ajax请求的方法。

你可以看到错误,即如何在这里

image http://s24.postimg.org/q0zj3vwhg/Error_Message.jpg

中止请求,如何延迟或使用Java脚本保持请求。

回答

1

您应该使用.done调用本身触发下一个批次的AJAX调用:

var keys = Object.keys(personScoreCollection.collection); 

(function next() { 
    if (keys.length) { 
     var index = keys.shift(); 
     $.when(UserSearch(index), 
       UsabilityScore(index), 
       UserConnection(index) 
     ).done(function(a, b, c) { 
        // process results 
     }, next); // recurse 
    } 
})(); // start loop immediately 

的代码,使所需的按键阵列,并且只是在一个时间转移从阵列的一个键,然后做出三个必需的AJAX调用。只有三次都完成后才开始下一批。

为了循环,它利用了如何通过.done多个回调,每个回调将依次被调用。如果您要反转这两个回调,则可以在处理当前一组结果时启动下一批(异步)提取。

注意,如果任何一个AJAX调用失败,因为.done功能的回调将不会被调用这个循环将中止。

0

可以使用setTimeout函数耽误一些工作。 一个例子:

var ms_pause = 50; // time between request in milliseconds 
var counter = 1; 

for (index in personScoreCollection.collection) { 
    //Get the 4th and 5th score simultaniously. 
    setTimeout((function(context_index){ 
     return function(){ 
      $.when(UserSearch(context_index), UsabilityScore(context_index), UserConnection(context_index)).done(); 
     } 
    })(index), ms_pause * counter); 
    counter += 1; 
}