Anar Kazimov Anar Kazimov - 3 months ago 11
Javascript Question

Why the code after loop executes before dom change inside of the loop?

I am writing a code that reads a name of the person from the textbox and then shows a sign/gesture for every letter in that name. Every letter in the name is read in the FOR loop which also changes gestures/signs according to the read letter. After loop stops working the page should refresh but for some unknown reason, the page refreshes before the loop ends.

I decided to imitate this situation in a brief code illustrated below. When you will run it you will see that alert appears before the code in the loop is executed. I also created a JSFiddle for convenience HERE.



function show_name(name) {
for (var i = 0, len = name.length; i < len; i++) {
if (name[i] == "H") {
var text = document.getElementById("text_tag");
text.innerHTML = "Hillary Clinton was a hot baby in the past :D";
}
}
alert("But Bill preferred Monica :(");
}

<input type="text" id="name" size="18" style=" font-size:17px; margin-left:4px; " onchange="show_name(this.value)" />
<p id="text_tag"></p>




Answer

your loop is correctly being executed. but you are getting the alert before your text appears in dom. because browsers render changes in batch so when it's finished with your show_name function it'll update the text. you can be sure by adding a console.log/alert inside your loop.

function show_name(name) {
    for (var i = 0, len = name.length; i < len; i++) {
         console.log(name[i]); //alert(name[i]);
        if (name[i] == "H") {
            var text = document.getElementById("text_tag");
            text.innerHTML = "Hillary Clinton was a hot baby in the past :D";
        }
    }
    setTimeout(function(){
         alert("But Bill preferred Monica :(");
    },50);
}
<input type="text" id="name" size="18" style=" font-size:17px; margin-left:4px; " onchange="show_name(this.value)" />
<p id="text_tag"></p>