User394839859 User394839859 - 5 months ago 71
Javascript Question

Calculate AJAX download speed

I would like to display the download speed in real time as a file is downloaded, however the following code is not working.

Speed
returns 0.0 for the entire download.

https.get(options, function (update) {
fileSize = (parseInt(update.headers['content-length']) / 1048576).toFixed(1);
startTime = (new Date()).getTime();
endTime = startTime;
update.on('data', function (chunk) {
file.write(chunk);
len += chunk.length;
fileDownloaded = (len / 1048576).toFixed(1);
endTime = (new Date()).getTime();
time = (endTime - startTime) / 1000;
speed = ((fileSize / time) / (1024 * 1024)).toFixed(2);
progressPercentage.html(fileDownloaded + ' MB / ' + fileSize + ' MB ' + speed + ' MB/s');
});
});

Answer

I think there is maybe a better solution, but here we go:

var startTime = (new Date()).getTime();
var downloadedLength = 0;

update.on('data', function (chunk) {
    // ...

    downloadedLength += chunk.length;

    var now = (new Date()).getTime();
    var speed = downloadedLength / (now - startTime); //bytes/second
    //speed / 1024 should return in kilobytes

    //...
});

Edit:

Consider using Date.now() instead of (new Date()).getTime(); for better performance