2014-07-09 88 views
0
for (var i = 0; i < 5; i++) { 

     (function(index) { 

      ajaxFuncHere(i); 


      //now you can also loop an ajax call here without problems: $.ajax({}); 
     })(i); 

    } 

我想延迟每个迭代300毫秒或什么的,我该怎么做?每次迭代,延迟执行

我试图把一个setTimeout的是这样的:

for (var i = 0; i < 5; i++) { 

     (function(index) { 

      setTimeout(function() { 
      ajaxFuncHere(i); 
      }, 300);   

      //now you can also loop an ajax call here without problems: $.ajax({}); 
     })(i); 

    } 

但是它没有给我想要的结果,而只是推迟,然后把他们都出来。

我如何能延缓自身完成功能后300毫秒,(我用的内封的原因)

+0

setTimeOut()不停止处理,它只是说“在X毫秒内执行此功能”。 – Nzall

回答

1

延迟它们递增每次迭代。

for (var i = 0; i < 5; i++) { 

    (function(index) { 

     setTimeout(function() { 
     ajaxFuncHere(index); 
     }, 300*(index+1)); 

    })(i); 
} 
+0

它看起来像使用它时,它的范围太远,因为如果我添加setTimeout内部函数未能完成它的任务,并且如果删除它可以工作 – John

+0

@John在匿名函数中使用'index'而不是'i' :'setTimeout(function(){ajaxFuncHere(index);},300 *(index + 1));'。 – freakish

+0

@确实,谢谢你的纠正。现在编辑。 – jlahd

0

答案很简单,就是用乘法:

for (var i = 0; i < 5; i++) { 

    (function(index) { 

     setTimeout(function() { 
     ajaxFuncHere(index); 
     }, 300 * 1);  //Will delay the script 

     //now you can also loop an ajax call here without problems: $.ajax({}); 
    })(i); 

} 

最好的解决方法是使用一个自调用回调函数完成了ajax。因为我不知道你的ajaxFuncHere的样子,生病asume是这样的:

function ajaxFuncHere(){ 
    $.ajax(...); 
} 

其更改为:

function ajaxFuncHere(){ 
    return $.ajax(...); 
} 

然后使用类似的东西:

//Remove the for 
(function loop(number, current) { 

    if(current === undefined) current = 0; 

    if(current < number) setTimeout(function() { 
     ajaxFuncHere(current).done(loop.bind(null, number, ++current)); 
    }, 300);   
})(5); //5 == number of iteration 

一旦ajax完成后,它会调用该函数并等待300 ms。

+0

它工作的第一次迭代,然后它说Uncaught TypeError:无法读取未定义的属性'完成' – John

+0

@John你可以告诉我你的'ajaxFuncHere()'? –

+0

它看起来像这样:http://pastebin.com/fUsfm2vB – John

0

您可以用tail-recursive function其在最后超时它的执行,并再次调用自身替换for循环:

var i = 0; 
var max = 5; 
var doLoop = function() 
{ 
    if(i < max) 
    { 
     ajaxFuncHere(i); 
     i++; 
     setTimeout(doLoop, 1000); 
    } 
}; 
doLoop(); 

function ajaxFuncHere(x) 
{ 
    // Do what you want to do. 
    // Look at the demo for an example. 
} 

这里有一个demo。只需更换您的ajaxFuncHere与我的,它应该工作得很好。