How can I cap the download speed of XHR2 in javascript

1k views Asked by At

I have implemented a "downloader" using XMLHTTPRequest, which I use to download files and parts of files using javascript. For testing and maybe also for real-world scenarios, I would like to limit the bandwidth this downloader takes.

One option I have in mind is to stop and start the downloader over and over again with setTimeout. This will stall the download of the next http block. But this is quite ugly...

Can I somehow stall the next request for chunk? maybe by putting some delay in the onreadystatechange event. Here's the code:

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

There are 0 answers