Search code examples
jqueryajaxhtmlfreeze

How can I call ajax synchronously without my web page freezing


I have some javascript that fires off about 100 calls to a php script. the php script uses up a lot of memory and takes a few seconds to complete, then returns a json response of pass or fail.

I don't want the ajax calls to be asynchronous as the server would come to a grinding halt running 100 instances of itself, so I tried using synchronous, the only problem being it freezes the webpage while it calls the script one call at a time.

How can I fire off the ajax calls one at a time and not freeze the page i'm on?

var a = [];
    a[0] = 'test';
    a[1] = 'hello';
    a[2] = 'another';

$(document).ready(function(){ 
  $.each(a, function(k,v) {
$.ajax({
  url:'/this-script-takes-a-few-seconds-to-complete.php',
  async:false,
  data: {foo: v},
  success: function(data){      
    console.log(data);  
  }
});
  });
});

Solution

  • You can put in in a function that performs the next call, and call this from your success handler, like this:

    $(function(){ 
      var i = 0;
      function nextCall() {
        if(i == a.length) return; //last call was last item in the array
        $.ajax({
          url:'/this-script-takes-a-few-seconds-to-complete.php',
          data: { foo: a[i++] },
          success: function(data){      
            console.log(data);  
            nextCall();
          }
        });
      }
      nextCall();
    });
    

    Though...the better approach would be to not do 100 calls, unless this is a test suite of some-sort, I'd re-visit the whole approach.