Introduction
This article describes how to create a bandwidth meter to measure the network speed for your web application.
Background
One of our clients requested to have a bandwidth meter for his web application. It was a big challenge to make a bandwidth meter in a browser. After thinking for several hours, I got an idea to make it using JavaScript. In this article, I will share my code to make a bandwidth meter using JavaScript.
Using the code
When a page is rendered to the browser, a stream of text is sent from the server. I used JavaScript and measured the time to transfer some dummy text. I then convert this time into a bandwidth measurement.
Below are the steps to create a bandwidth meter using JavaScript:
- Get the starting time before transferring dummy text:
<script language="javascript" type="text/javascript">
time = new Date();
time1 = time.getTime();
</script>
- Transfer a dummy text of 45000 bytes in the HTML comment tag. We use this text to measure the time to transfer 45000 bytes to the browser.
<!---->
<!---->
- Here comes the real stuff. We have the start time before transferring the 45000 bytes, and the current time. We calculate the time difference to get the time taken to transfer 45000 bytes. Using this time difference, we calculate the actual bandwidth used to transfer 45000 bytes. That's it; now you are done with your own bandwidth meter :)
<script language="javascript" type="text/javascript">
time = new Date();
time2 = time.getTime();
ttime = time2 - time1;
if (ttime == 0)
ttime = .1;
ttime = ttime / 1000; kbps = 45 / ttime;
kbps = kbps * 8; kbps = Math.round (kbps);
document.getElementById("lblBandwidth").innerHTML=kbps + " kbps";
</script>
History
- 22 December, 2007: Initial version.