Question

I have a loop which sends AJAX requests and it works well with 5 files or so, but when I try to upload more than 5 files. The browser stops.

Is there any way to create or define a maximum number of simultaneous connections and after they finish, starting the other?.

for (i=0;i<=files.length;i++) {

var http = new XMLHttpRequest();
var data = "type=ZIP&file=" + base_64_encode(files[i]);

http.open("POST", "update.php");
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.send(data);

}
Was it helpful?

Solution

If I understand right, you just want to throttle them? You can do this by keeping track of how many are concurrent, maintaining a queue of requests in excess of the max concurrency, and attaching a callback to your requests that updates the current concurrency value and triggers that next queued function if applicable:

function throttleFileUploads(files, maxConcurrent) {
  var queue = [];
  var currentlyActive = 0;

  function moreAllowed() { return (currentlyActive < maxConcurrent); }

  function uploadFile(file, callback) {
    currentlyActive += 1;
    var http = new XMLHttpRequest();
    var data = "type=ZIP&file=" + base_64_encode(file);

    http.open("POST", "update.php");
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    http.onreadystatechange = function() {
      if (http.readyState == 4) { callback(); }
    };

    http.send(data);
  }

  function finished() {
    currentlyActive -= 1;
    if (moreAllowed() && queue.length) { queue.pop()(); }
  }

  files.forEach(function(file) {
    var action = uploadFile.bind(null, file, finished);
    if (moreAllowed()) {
      action();
    } else {
      queue.push(action);
    }
  });
}

(Note -- I didn't test it, but I think the idea is sound.)

throttleFileUploads(files, 5);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top