TheRealPir TheRealPir - 3 months ago 5x
HTML Question

writing to html from a javascript loop "when it happens"

I am trying to figure out, how to write to a div in "real time" from javascript. When I run the code, any text from the loop is shown only once both loops have executed, but really the way (I think I wrote it), it should be popping out line by line.

See an example

JsFiddle Demo

I would like it to work just like in a chrome developer tool console, where you see right away what is happening (using console.log).

I know I could put it all to a string or array and print it in one go outside the loops, but I really need to see it as it is happening.

I am sure there must be already a solution somewhere, but I just can't find any leads (maybe not using the right words for google). Any info would be highly appreciated.

Made output in console and HTML the same, to make it less confusing and allow for better comparison
JSFiddle Demo 2


The problem is, that your while loops are to fast. You would not see the output live. The browser needs some time to update the document. The reason you can see it each-by-each in the console, is just because the console is to slow. The console outputs the lines with a delay. When you see the last entry in your console is comming up, your code has already ended a long time before. Your code execution is mutch faster than the console. So this is not in time too.

You could now try to give the browser some time in your loop execution, to output the data and let the browser render the change. But because you used loops there, you can't make it async or create a delay to output the values first, before starting with the next one. But you can switch the code to self executing functions and trim down the time a bit for a smooth output in the browser before printing the next line.

And if you create such big loops, you should really take care of your code. It is not a good idea to let jQuery search the #log div in every loop again. Just do it once before the loops. And don't use an array for this simple string operations. This slows it down even more.

var log = $("#log");
var generateTestCases = 3000;

(function next(amount) {
    if( amount ) {
        var repeatIF2 = 10;
        var trackingString = amount + ";";

        (function output(count) {
            if( count ) {
                trackingString += count + ";";
                log.append('<div>' + trackingString + '</div>');

                if( --count ) {
                    // this line slows down the output
                    // change the time for faster or slower output
                    setTimeout(output, 50, count);
                } else {

Working example.