每次迭代,都会延迟执行

时间:2014-07-09 13:47:01

标签: jquery

    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毫秒(我之所以使用闭包的原因)

3 个答案:

答案 0 :(得分:1)

递增延迟。

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

    (function(index) {

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

    })(i);
}

答案 1 :(得分: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是什么样子的,那就像这样:

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毫秒。

答案 2 :(得分: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替换为我的,它应该可以正常工作。

相关问题