0

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!

2
  • Works fine for me. Commented Apr 17, 2018 at 5:36
  • The browser instance handling your page is single threaded. The change to the DOM happens right away. However, while your script is running, the browser is blocked and not able to run its layout manager which updates the page (from semi-related question: stackoverflow.com/a/5627068/2181514) Commented Apr 17, 2018 at 7:02

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

@user2986994 My pleasure... :)
0

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>

Comments

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.