Skip to content

Instantly share code, notes, and snippets.

@socheatsok78
Last active April 28, 2021 04:02
Show Gist options
  • Save socheatsok78/c573b573b4adafa43da163df3843aaa9 to your computer and use it in GitHub Desktop.
Save socheatsok78/c573b573b4adafa43da163df3843aaa9 to your computer and use it in GitHub Desktop.
MLHttpRequest: progress event handler

Usage with axios

const handler = HttpProgressHandler()

axios.get('/download?ID=12345', {
  onDownloadProgress: function (e) {
    const { speed, percent, completed } = handler(e)
    console.log(completed + 'MB (' + percent + '%) ' + speed + 'KB/s')
  }
})
export function HttpProgressHandler () {
let lastNow = new Date().getTime()
let lastKBytes = 0
return function onHttpProgressHandler (e) {
if (!e.lengthComputable) return
const now = new Date().getTime()
const bytes = e.loaded
const total = e.total
const percent = bytes / total * 100
const kbytes = bytes / 1024
const mbytes = kbytes / 1024
const uploadedkBytes = kbytes - lastKBytes
const elapsed = (now - lastNow) / 1000
const kbps = elapsed ? uploadedkBytes / elapsed : 0
lastKBytes = kbytes
lastNow = now
return {
speed: kbps.toFixed(2),
percent: percent.toFixed(2),
completed: mbytes.toFixed(2)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment