3

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.

Community
  • 1
  • 1
Irf92
  • 319
  • 2
  • 14
  • 1
    Possible duplicate of [Is there a JavaScript alert that doesn't pause the script?](https://stackoverflow.com/questions/303720/is-there-a-javascript-alert-that-doesnt-pause-the-script) – Nisarg Shah Sep 07 '18 at 10:05
  • 1
    You could listen for the button value to change, and fire the alert after the change, or am I wrong? –  Sep 07 '18 at 10:18
  • @D.Schaller no, that is a better idea. But What is the reason for this behavior of JS? – Irf92 Sep 07 '18 at 10:21

3 Answers3

1

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.

José Antonio Postigo
  • 2,674
  • 24
  • 17
  • I wouldn't call it 'thread execution' because that might confuse people - JavaScript doesn't have real threads. – ChrisM Sep 07 '18 at 10:16
  • 2
    Yep, Javascript execution is a single thread process, but a thread is a thread, right? – José Antonio Postigo Sep 07 '18 at 10:18
  • Threads, generally, are components of a process that can be managed independently by the scheduler. While what you say is technically correct mentioning it can be confusing in this context because JavaScript has no concept of or access to the underlying threads. It probably doesn't matter much - but I just would say that "the JavaScript execution pauses" or "the JavaScript engine pauses" – ChrisM Sep 07 '18 at 10:25
1

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)
}
Armin
  • 373
  • 2
  • 13
1

For a proper explanation of why it happens, see this answer here.

TL;DR see Josè's answer.

Here's how you can quickly fix this

setTimeout(_=>alert('hi'))
rmn
  • 1,119
  • 7
  • 18