JQuery Ajax loop delay

Tags: , , ,



i am trying to make a delay in my ajax data so the loop become a little bit slower ! and here is my code

$(document).ready(function (){
$('#button').click(function(){

 $('#hide').show();
 var data = $('#textarea').val();

 var arrayOfLines = data.split("n"); 

 var track = JSON.stringify(arrayOfLines);
 var item = "";

 var lines = $('#textarea').val().split('n');

here is the loop

 for (var i = 0; i < lines.length; i++) {
     item = lines[i];
            $.ajax({
            type: 'GET',
                url: 'cookie.php',
                dataType: 'html',
                data: 'data=' + item+'&cookie='+track,
                success: function(msg){
                    $('#results').append(msg);

                }

                });
 }

});

Answer

Using recursion, you could put in a function sendToServer and pass through the array lines, starting index 0. The function will run from 0 to lines.length. This way you won’t DDOS your server 🙂

If you really need some kind of arbitrary delay, you can include a timeout on the sendToServer function call – in the example it is set to 5 seconds.

 var sendToServer = function(lines, index){
   if (index > lines.length) return; // guard condition
   item = lines[index];
   if (item.trim().length != 0){
     $.ajax({
       type: 'GET',
       url: 'cookie.php',
       dataType: 'html',
       data: 'data=' + item+'&cookie='+track,
       success: function(msg){
         $('#results').append(msg);             
         setTimeout(
           function () { sendToServer(lines, index+1); }, 
           5000 // delay in ms
         );             
       }
     });
   }
   else { sendToServer(lines, index+1); }
};

sendToServer(lines, 0);


Source: stackoverflow