John
John

Reputation: 3060

Each iteration, delay the execution

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

        (function(index) {

           ajaxFuncHere(i);


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

    }

I would like to delay each iteration with say 300 ms or something, how can I do that?

I tried putting a setTimeout like this:

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

    }

However its not giving me the desired result, but instead just delaying and then put them all out.

How can I delay each iteration with 300 ms after the function itself is completed, (the reason I use the closure within)

Upvotes: 0

Views: 71

Answers (3)

Jonast92
Jonast92

Reputation: 4967

You can replace the for-loop with a tail-recursive function which timeouts at the end of it's execution and calls itself again:

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.
}

Here's a demo. Just replace your ajaxFuncHere with mine and it should work just fine.

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33880

The simple answer is to use a multiplication :

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

}

The best solution is to use the ajax done callback with a self-calling function. Since i dont know how your ajaxFuncHerelook like, ill asume something like this :

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

Change it for that :

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

then Use something like that :

//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

Once the ajax is done, it will recall the function and wait 300 ms.

Upvotes: 0

jlahd
jlahd

Reputation: 6303

Delay them incrementally.

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

    (function(index) {

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

    })(i);
}

Upvotes: 1

Related Questions