-1

Hi I'm trying to display the iterations of a while loop continuously in a text box. However, the browser waits till the loop finishes then displays the final iteration only.
I'm using this loop to run a complex function which means the iterations will be slower and can be seen if displayed in the console:

For example, I'm trying to do something like this. in HTML:

    <p>
      <label>This is generation number</label>
      <input type = "number"
             id = "generation"
             />
    </p> 

in Javascript:

function Run(){

var i=0;

while (i<500) { 

document.getElementById('generation').value= i;

i++
        }
}
Waleed
  • 39
  • 3
  • 2
    Possible duplicate of [Javascript async loop processing](https://stackoverflow.com/questions/9772400/javascript-async-loop-processing) – Michael Jasper Dec 20 '17 at 18:58
  • You cannot do this with a synchronous `while` loop. Use a recursive approach and `requestAnimationFrame` instead. Of course, this will be more complicated in your real code. – Bergi Dec 20 '17 at 19:03

1 Answers1

1

You can not do it synchronously (No while loop). This locks up the browser and does not allow anything else to happen. No draw cycle can happen and it looks like nothing it changing.

Try breaking it into a function that only does one step and then call it over and over through a timeout.

    var updateEl = document.getElementById("generation");
    var i;

    function doStep() {
      //super crazy code
      updateEl.value = i;
      i++;
      if (i < 500) {
        timeout = setTimeout(doStep);
      }
    }


    function Run() {
      i = 0;
      doStep();
    }

If you need this process to be as fast as possible you want setTimeout. If you want to synchronize with the animation buffer of canvas or speed is not a real issue then use requestAnimationFrame.

UPDATE

To match what @Brian is saying in his comment below:

var updateEl = document.getElementById("generation");

function doStep(i) {
  //super crazy code
  updateEl.value = i++;
  if (i < 500) {
    timeout = setTimeout(() => doStep(i));
  }
}


function Run() {
  doStep(0);
}
<p>
  <label>This is generation number</label>
  <input type="number" id="generation"/>
</p> 
<button onclick="Run()">Run</button>
Intervalia
  • 10,248
  • 2
  • 30
  • 60