0

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.

Duklas
  • 83
  • 1
  • 4
  • Does this answer your question https://stackoverflow.com/questions/14774245/how-to-change-progress-bar-in-loop ? https://www.w3schools.com/howto/howto_js_progressbar.asp – Nishant Jun 19 '20 at 20:54

1 Answers1

0

Long running loops in JS freezes the UI refresh, to show the progress of data, you may need to move the data processing logic to web worker. You can read about web worker on the following link.

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

Syed Jailani
  • 161
  • 5