Why the HTML DOM event doesn't affect immediately on the same DOM element?

Viewed 79

I'm writing the code to change the Button element value when the click event is executing.

But Until it finishes it doesn't affect the button element value.

I attached the fiddle example which will give you a good idea of what I'm talking about.

function myFunction() {
 document.getElementById("demo").innerHTML = "Hello World";
 alert('hi')
}

Even the button element innerHTML changed before alert, it doesn't affect the UI.

How can I accomplish, before the alert is executed I need to change the button text?

Thanks.

3 Answers

It's because the Javascript thread execution stops until you click the confirm button in the alert. You would say: but why? if the HTML change instruction was executed before. Well, although the Javascript code was executed, the browser still didn't make the changes in the DOM.

Closest to threading in JS is settimeout function, this is not ok to do but here is how would it look like if you use it

 function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World";
  setTimeout(function(){
      alert('hi')
  },1000)
}
Related