I'm trying to display the progress of a file being loaded through an XMLHttpRequest using bootstrap's progress bar. Unfortunately the progress bar only updates when the file has loaded (ie it stays at 0% while the file is loading, then jumps to 100% when it's done). I realise this is because the UI and javascript are run on the same thread but I don't know how to get around it. I've tried numerous alternatives such as intervals and workers.
Here is my code:
Loading the file and running the progress eventListener:
var xhr = createXHR();
xhr.open('GET', path, true);
xhr.addEventListener("progress", updateProgress);
xhr.onreadystatechange = function(evt) {
...
}
updateProgress funtion:
var percentComplete = 0;
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
percentComplete = oEvent.loaded / oEvent.total;
console.log(percentComplete);
} else {
//
}
}
This code is run once the file starts loading, attempts to use setInterval as it is asyncronous:
var progress = setInterval(function(){
//update the progressbar
$('#progress-bar').css('width', Math.round10(percentComplete*100, 2)+'%');
if(percentComplete==1){
$('#progress-modal').modal('toggle'); //Close the progress bar
clearInterval(progress); //clear the setInterval
}
}, 50)
I thought that setInterval being asyncronous would solve this, but it doesn't. The console.log method works well - if I could update the progressbar similarly that would be perfect. Could someone point out what I'm doing wrong?