在下面的代码中,我试图计算一个图像的下载速度,但速度是无穷大的.我究竟做错了什么?
var imageAddr = "/images/image.jpg" + "?n=" + Math.random(); var startTime,endTime; var downloadSize = 200000; var download = new Image(); download.onload = function () { endTime = (new Date()).getTime(); showResults(); } startTime = (new Date()).getTime(); download.src = imageAddr; function showResults() { var duration = Math.round((endTime - startTime) / 1000); var bitsLoaded = downloadSize * 8; var speedBps = Math.round(bitsLoaded / duration); var speedKbps = (speedBps / 1024).toFixed(2); var speedMbps = (speedKbps / 1024).toFixed(2); alert("Your connection speed is: \n" + speedBps + " bps\n" + speedKbps + " kbps\n" + speedMbps + " Mbps\n" ); }
解决方法
持续时间可能会超出0,并且正数除以零可以产生JavaScript中正无穷大的特殊值.