如何在javascript中限制XHR2的下载速度

时间:2012-02-03 11:31:34

标签: javascript http xmlhttprequest xmlhttprequest-level2

我使用XMLHTTPRequest实现了一个“下载器”,我用它来使用javascript下载文件和部分文件。对于测试,也可能对于真实场景,我想限制下载器所需的带宽。

我想到的一个选择是使用setTimeout一遍又一遍地停止和启动下载程序。这将停止下一个http块的下载。但这太丑了......

我可以以某种方式停止下一个块的请求吗?也许是通过在onreadystatechange事件中加入一些延迟。这是代码:

download:function (start, end) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", this.url, true);

    if (end) {
        xhr.setRequestHeader("Range", "bytes=" + start + "-" + end);
    }
    else {
        if (start && start > 0) {
            xhr.setRequestHeader("Range", "bytes=" + start);
        }
        else {
            start = 0;
        }
    }
    // Hack to pass bytes through unprocessed.
    xhr.overrideMimeType('text/plain; charset=x-user-defined');

    thi$ = this;
    xhr.onreadystatechange = function() {
        if (this.stopped) {
            xhr.abort();
        }
        if (typeof this.index == "undefined")
            this.index = 0;

        if (this.readyState >= 3 && this.status == 200) {
            var content = this.responseText;
            thi$.handleContent( content.substring(this.index), this.index);
            this.index = content.length;
        }
    }

    xhr.send(null);
}

0 个答案:

没有答案