Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do my changes to the dom not show up until after function has run

my eval() call is fairly intensive and takes about a second to generate each solution.

Therefore it takes about a second to generate each paragraph element (which I then append to the dom - document.getElementById('project_euler_solutions').appendChild(p); ).

Therefore I expected each paragraph to appear on the webpage about a second apart. (so after about 40 seconds I would have 40 paragraphs say).

However, when I click the button, Nothing happens for 40 seconds, and then all the solutions appear at once.

How come it waits for all of them to finish before it updates the dom?

I thought each paragraph would appear as soon as it was appended to the dom

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js"></script>
    <script src="/statics/project_euler.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("button").click(function(){
                for (var i in window) {
                    if (i.slice(0,5) == "solve") {
                        var p = document.createElement('p');
                        p.innerHTML = "running: " + i;
                        document.getElementById('project_euler_solutions').appendChild(p);
                        var p = document.createElement('p');
                        p.innerHTML = "Solution: " + eval(i + "()");
                        document.getElementById('project_euler_solutions').appendChild(p);
                    }
                }
            });
        });
    </script>
</head>

<body>
<div id="project_euler_solutions"><button>Calculate solutions</button></button></div>
</body>
</html>
like image 515
robert king Avatar asked Jan 21 '26 23:01

robert king


1 Answers

Javascript runs in the same thread as UI, so you need to give the control back for the DOM to re-draw all the changes.

like image 124
zerkms Avatar answered Jan 23 '26 13:01

zerkms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!