4

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);
}
whadar
  • 4,181
  • 4
  • 19
  • 21
  • `setTimeout()` is basically your only choice. You can't make a browser stall or wait. – Pointy Feb 03 '12 at 11:53
  • 1
    Where would you put setTimeout? in the onreadystatechange block won't do the magic... Thanks – whadar Feb 03 '12 at 12:42
  • You'd use the timeout to control when you *start* each XHR. Once you start it, you can't control how fast the server is going to return results (unless you control the server, of course, but then that wouldn't have much to do with JavaScript). – Pointy Feb 03 '12 at 13:03

0 Answers0