0

I'm currently doing some exercises with JavaScript (Euler problems) and decided to try out an idea for creating a progress bar for problems that use nested loops and take a few seconds. It's just an image of an empty progress bar layered underneath a full one, with a JavaScript function set to change the width of the full bar periodically.

However, this change doesn't seem to happen until after all of the calculations are finished. Does JavaScript put DOM manipulation on hold while it does calculations? If so, is there a simple way around this?

Here's the code I'm running.

JavaScript code:

    function updateProgress(calc){
        var recorded_calculations = 90357988; //(pre-recorded number)
        var percent = (calc / recorded_calculations) * 100;
        document.getElementById("full-bar").style.width = percent + "%";
        if(percent == 100){
            return;
        }
        setTimeout(function(){
            updateProgress(calculations);
        }, 1);
    }

    var calculations = 0;

    updateProgress(calculations);

    for(lots of increments){
        calculations++;
        //Logic here
        for(lots of increments and){
            calculations++;
            //Logic here

And CSS code:

#background-bar{
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 1;
    width: 100%;
}

#full-bar{
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 2;
    width: 0%;
    overflow: hidden;
}
Avi K.
  • 1,734
  • 2
  • 18
  • 28
sadq3377
  • 827
  • 1
  • 5
  • 17
  • Remove the `setTimeout()` and place `updateProgress(calculations)` where you have `//Logic here`. – Tigger Jun 04 '16 at 23:58

2 Answers2

0

The UI will block while the calculation is executing.

I answered a very similar question recently.

https://stackoverflow.com/a/37092024/4567456

The same applies here.

Community
  • 1
  • 1
VRPF
  • 3,118
  • 1
  • 14
  • 15
0

JavaScript is single-threaded. If some other code is being executed when the Timeout is expected to be called it will wait until that is finished before the timeout function is called...

So basically your for loop is going to be blocking the updateProgress function until it completes, so it's not much use as a progress bar.

Most project euler problems are such that with an efficient Algorithm it should be almost instant to run most problems. If you are creating the progress bar to track problems that are taking a long time to complete, then it probably means you could/should find a better solution.

if you want to update the progress you need to call the function from inside your for-loop.

you could just call update progress if (calculations %1000 === 0) or something so it isn't calling it constantly.

Koborl
  • 235
  • 1
  • 11