I have a loop that processes data for a while, so I'd like to show a progress bar while the loop is processing. I've tried updating the progress bar within each loop iteration:
let data = new Array(1000000); //large input data
let progress_bar = document.getElementById('progress_bar');
let progress_text = document.getElementById('progress_text');
let progress = 0;
let full = data.length;
for (let row of data) {
progress_bar.style.width = (100 * progress / full) + '%';
progress_text.innerHTML = Math.round(100 * progress / full) + '%';
processData(row);
progress += 1;
}
function processData(input) {
//process the line of data
}
#progress_track {
height: 5px;
width: 80vw;
margin-left: 10vw;
background: #888;
}
#progress_bar {
background: #54f;
height: 5px;
width: 0;
}
#progress_text {
font-size: 18px;
width: 100vw;
text-align: center;
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id='progress_track'>
<div id='progress_bar'></div>
</div>
<div id='progress_text'>0%</div>
</body>
</html>
As you can see, it updates all at once at the end.
Here it explains that JavaScript only updates the UI at the end of something so rapid, so I tried replacing
progress_bar.style.width = (100 * progress / full) + '%';
progress_text.innerHTML = Math.round(100 * progress / full) + '%';
with
if ((progress % 1000000) == 0) {
progress_bar.style.width = (100 * progress / full) + '%';
progress_text.innerHTML = Math.round(100 * progress / full) + '%';
}
but that yields the same result.
I also tried using setTimeouts and setIntervals, but my understanding of callbacks isn't that great, so I ended up accidentally accessing the data before it was processed.