Is it possible to retrieve an jQuery ajax response, then adding a print delay of data by iterating through an array

Viewed 63

Inside a typical ajax response you would simply just print out the data to a div. I want to take the data response and split it up into an array, then iterate that array and add a random delay between appends.

In this specific example I am splitting up the response into each

tag. Then I am looking to add a delay before printing these responses.

So far this has not worked for me. It will only showcase the data response in full, even if I iterate through the array with setTimeout.

        //start the ajax
        $.ajax({
            //this is the php file that processes the data and send mail
            url: "/a_example.php?sim",  
            target:    '#crap',   // target element(s) to be updated with server response 
            //GET method is used
            type: "POST",

            //pass the data         
            data: data,     

            //Do not cache the page
            cache: false,

    success: function(data) {
                  var patt = /<p>(.*?)<\/p>/g;
                  var result = data.match(patt);
                var i;
                //alert(result.length);
                for (i = 0; i < result.length; i++) {
                    showResultMock(result[i]);

                }               


    },                  

    complete: function() {

        }

        });

function showResultMock(result){
 setTimeout(function(){  $('#modaldraftdetails .modal-body .draft-results').append(result); }, 2000);
}   
3 Answers

Try using recursion instead of iteration. Something like this:

const $resultsContainer = $('#results')
const results = [1,2,3]

function showResults(results) {
  if (!results.length) return
  setTimeout(function(){
    const result = results.shift()
    $resultsContainer.append(`<p>${result}</p>`)
    showResults(results)
  }, 2000)
}

showResults(results)

You can use a function recursively and use Math.random() to add a random delay like below:

let ctn = $("#ctn"),
  results = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  i = 0,
  maxDelay = 2000;

const printVal = val => {
  if (i < results.length) {
    //console.log(val);    
    ctn.append(`<span>${val}</span>`)
    setTimeout(() => {
      i++;
      printVal(results[i]);
    }, Math.random() * maxDelay)
  }
}

printVal(results[i])
span{ margin: 5px; font-family: courier; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ctn"></div>

While you iterate through the results, you basically create a pack of setTimeouts at the same time. Therefor those setTimeouts finish also at the same time.

Try a recursive solution, something like this:

/* Put this into the "success" callback */
var results = data.match(patt);
showResultMock(results, 0);

/* And this is your recursive fucntion's definition */
function showResultMock(results, i){
    if (i < results.length) {
        setTimeout(function(){  
            $('#modaldraftdetails .modal-body .draft-results').append(results[i]);
            showResultMock(results, ++i);
        }, 2000);
    }
}   
Related