JSFiddle - React, Tailwind, and code Playground
by icodeforlove
HTML
<span id="megabits"></span>
<div id="progressbar"><div></div></div>
CSS
body {
background: #ccc;
}
#megabits {
margin-top: 150px;
display: none;
text-align: center;
font-size: 62px;
font-family: helvetica;
color: #007bdc;
}
#progressbar {
width: 500px;
position: relative;
margin: 0px auto;
margin-top: 175px;
background-color: black;
border-radius: 13px; /* (height of inner div) / 2 + padding */
padding: 3px;
}
#progressbar div {
background-color: #007bdc;
height: 20px;
border-radius: 10px;
width: 0%;
-webkit-transition: width 250ms 0 ease-out;
}
JavaScript
function BandwidthTest () {
}
BandwidthTest.prototype = {
container: 'http://93c5d38207718e93eb05-710537005de6055213f4f63880c17650.r32.cf2.rackcdn.com/',
sizes: [250, 500, 750],
test: function (tests, callback, progress) {
var self = this,
results = [];
this.latencyCheck(function (latency) {
function test () {
self.downloadFile(latency, 750, function (megabits) {
results.push(megabits);
if (results.length < tests) {
if (progress) progress((results.length / tests).toFixed(2), self.average(results).toFixed(2));
test();
} else {
callback(self.average(results).toFixed(2));
}
});
}
test();
});
},
downloadFile: function (latency, kilobytes, callback) {
if (this.sizes.indexOf(kilobytes) === -1) throw(new Error('Unsupported FileSize'));
var start,
request = new XMLHttpRequest();
request.addEventListener('readystatechange', function() {
if (this.readyState == 4 && this.status == 200) {
var duration = (new Date() - start - latency) / 1000,
megabytes = (kilobytes / 1024),
megabits = (megabytes / duration)*8;
callback(megabits);
} else if (this.readyState === 2) {
start = new Date();
}
});
request.open('GET', this.container + kilobytes + 'KB?r=' + Math.round(Math.random() * 1000000), true);
request.send();
},
latencyCheck: function (callback) {
var self = this,
tests = 15,
results = [];
function check () {
var start = new Date(),
request = new XMLHttpRequest();
request.addEventListener('readystatechange', function() {
if (this.readyState == 4 && this.status == 200) {
results.push(parseFloat(new Date() - start));
if (results.length < tests) {
check();
} else {
callback(parseFloat(self.average(results).toFixed(2)));
}
}
});
request.open('GET', self.container + '0Byte?r=' + Math.round(Math.random() * 1000000), true);
request.send();
}
check()
},
average: function...