Skip to content

Instantly share code, notes, and snippets.

@jnm
Last active September 11, 2015 15:22
Show Gist options
  • Save jnm/8d5215b0e21c62a7995d to your computer and use it in GitHub Desktop.
Save jnm/8d5215b0e21c62a7995d to your computer and use it in GitHub Desktop.
Test a connection by repeatedly downloading a file
<html>
<head><title>download test</title></head>
<body>
<input type="text" id="status" style="width: 100%">
<div id="log"></div>
<script>
/*
mostly cookbooked from
https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
*/
var i = 0;
var stopAfter = 25;
var url = "https://kc.kbtdev.org/static/1m.zero";
var statusEl = document.getElementById("status");
var logEl = document.getElementById("log");
var startTime = 0;
function startDownload() {
var oReq = new XMLHttpRequest();
oReq.addEventListener("progress", updateProgress, false);
oReq.addEventListener("load", transferComplete, false);
oReq.addEventListener("error", transferFailed, false);
oReq.addEventListener("abort", transferCanceled, false);
startTime = (new Date()).getTime();
oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + startTime, true);
oReq.send();
}
// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
var timeElapsed = ((new Date()).getTime() - startTime) / 1000;
var kilobytesPerSecond = Math.floor(oEvent.loaded / timeElapsed / 1000);
if (oEvent.lengthComputable) {
var percentComplete = Math.floor(oEvent.loaded / oEvent.total * 100);
statusEl.value = "Rate: " + kilobytesPerSecond + " kB/s; " + percentComplete + "% done";
} else {
// Unable to compute progress information since the total size is unknown
statusEl.value = "Rate: " + kilobytesPerSecond + " kB/s; " + oEvent.loaded + "bytes done";
}
}
function transferComplete(oEvent) {
var timeElapsed = ((new Date()).getTime() - startTime) / 1000;
var kilobytesPerSecond = Math.floor(oEvent.loaded / timeElapsed / 1000);
output = ("<p>Transfer " + ++i + " completed in " + timeElapsed + " seconds: ");
output += (oEvent.loaded + " bytes; " + kilobytesPerSecond + " kB/s</p>");
logEl.innerHTML += output;
if(i < stopAfter) {
startDownload();
}
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
startDownload();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment