Search code examples
javascriptjquerydelayeach

How to make delay between each loops of jQuery.each function?


I have this-like code:

$('li').each(function(){
   var data = $(this).text();
   requestFunction(data, function(status){
       if ( status == 'OK' ) do stuff...
   });
});

So, i need to do some delay between using function "requestFunction()". How could i do this? Hope it understandable, thanks.


Solution

  • setTimeout at an increase time:

    $('li').each(function(indexInArray){
       var data = $(this).text();
       setTimeout( function () {
           requestFunction(data, function(status){
               if ( status == 'OK' ) do stuff...
           });
       }, indexInArray * 500);
    });
    

    if you loop over these elements, we want to increase the timeout or else all the request would fire at the same time if not delayed, but only after our 500 ms timeout.

    • Time Start: 0 ms
    • First Request: 0 ms (500 * 0)
    • Second Request: 500 ms (500 * 1)
    • Third Request: 1000 ms (500 * 2)