Javascript output during function loop

Is there an easy way to output content when inside a Javascript loop, rather than have it display on screen after the loop has completed.

Code e.g:

var c = 0;
while (c <=1000 ){ //100000
  run();
  c++;
}
function run() {
  console.log(c);
  $('#data').append(c);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<div id="data"></div>

It outputs to console straight away (during loop) but on screen does not.

Hoping someone can assist. Thanks!

3 answers

  • answered 2018-04-17 05:34 Mike Poole

    Are you wanting to write it to the webpage?

    If so then you can write it to a div using the InnerHTML

    document.getElementById("yourDivID").innerHTML = yourString;
    

  • answered 2018-04-17 05:34 Arvind

    Try using clousres and setTimeout:

    function run(c) {
      console.log(c);
      $('#data').append(c + ', ');
    }
    
    $(function() {
      for (var c = 1; 999 > c; c++) {
        (function(c) {
          setTimeout(function() {
            run(c);
          }, 1);
        })(c);
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="data"></div>

  • answered 2018-04-17 05:34 Roshana Pitigala

    Your browser's Javascript engine is too fast thus you cannot see the changes in real time. So set a timer and slow down the process.

    Run the below code and see the magic happens...

    var c = 0;
    $(document).ready(function () {
        run();
    });
    
    function run() {
        var timer = setInterval(function () {
            //console.log(c);
            $('#data').append(c + "\n");
            if (c++ == 1000) {
                clearInterval(timer);
            }
        }, 12); //set time in milliseconds
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="data"></div>

    These are the changes made to your code :

    • Removed the while loop and replaced it with setInterval()
    • Added $(document).ready() function to make sure the run() is executed after the DOM is fully loaded.