如何在javascript中定义最大连接数

时间:2014-01-19 22:53:03

标签: javascript forms connection max send

我有一个发送AJAX请求的循环,它适用于5个左右的文件,但是当我尝试上传超过5个文件时。浏览器停止了。

有没有办法创建或定义最大数量的同时连接,并在完成后启动另一个?

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

}

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你只想扼杀它们?您可以通过跟踪多少并发,维护超过最大并发的请求队列,并将回调附加到更新当前并发值的请求并触发下一个排队函数(如果适用)来执行此操作:

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

(注意 - 我没有测试它,但我认为这个想法很合理。)

throttleFileUploads(files, 5);