Search code examples
javascripthtmlloopsdomdom-manipulation

Loop blocks DOM Manipulation


I have a simple counting loop that counts to 10000 and logs every number to the console. Before i start the loop i want to write "TEST" to the body in my html. Although i do this before i start the loop it appends "TEST" to the body only after the loop is done. However i can log something to the console before starting the loop. I think i am blocking the browser thread or something, i don't know how to write this in a non blocking manner. I have been trying to figure out this Problem for quite some time. Your Help would be much appreciated !!!

My HTML code:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<button onclick="myfunc()">click me</button>

</body>
<script src="index.js"></script>
</html>

My javascript code:

function myfunc() {
    var h1 = document.createElement("h1").innerText = "TEST"
    document.body.appendChild(h1) //appends only after loop is done
    console.log("test") // this works
    for (var i = 0; i < 10000; i++){
        console.log(i)
    }
}

Solution

  • One solution is to put your loop code in a timeout and set the delay to 1 millisecond

    function myfunc() {
        var h1 = document.createElement("h1")
        h1.innerText = "TEST"
        document.body.appendChild(h1) //appends before the loop
        console.log("test") // this works
        setTimeout(()=>{
          for (var i = 0; i < 10000; i++){
              console.log(i)
          }
        },1)
    }
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
    <button onclick="myfunc()">click me</button>
    
    </body>
    <script src="index.js"></script>
    </html>