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.

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Took me a while to understand how web workers work, but once I was able to implement it, it worked great!
Glad to hear. It is a quite a useful feature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.