Parallel AJAX requests in jQuery

When you for instance have a ajax call in a function 'doCall', just start this function for an x-amount depening on the 'threads' you want.

doCall(x);
doCall(x);
doCall(x);

Now you have 3 threads. To keep it going, 'restart' the function in the function. So in the doCall Function you have an other doCall(x) to 'keep the thread alive'.

You will have some sort of 'loop', and the requests will keep getting fired async.


$.ajax() is an asynchronous function which initiates a request and then returns immediately. So if you call it multiple times in a row, it will create concurrent requests.

Your code still runs on a single thread, but the HTTP requests happen in parallel in the background and jQuery invokes your callbacks as they return data. So you get parallelism without having to deal with threads directly.

In your GlobalCheck():

var CONCURRENT_REQUESTS = 4;

while (done < CONCURRENT_REQUESTS) {
  SingleCheck(done++);
}

will start four parallel requests, and your existing code will trigger a new request each time one finishes, so you will always have 4 parallel requests running. And because your code only runs on a single thread, you don't have to worry about concurrency issues with your done variable etc.

For more concurrent requests, just increase the value of CONCURRENT_REQUESTS, but note that very quickly you'll hit the browser's limit of concurrent requests to a single domain - it varies per browser but it's always a pretty small number. See this answer for specifics.