JQuery Ajax loop delay

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

                }

                });
 }

});

Answers 1

  • Don't send request to server in for loop. It can take down the server. Instead of what you did , you can do this :

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

Related Articles