Why alert() dialog shows first regardless of order in the code?

后端 未结 3 1766
感动是毒
感动是毒 2020-12-12 02:34

In the code sample below, I expect the text in div to change first.

But the text changes only after I click ok in the alert dialog.

相关标签:
3条回答
  • 2020-12-12 02:59

    Most browsers render changes to the DOM only between JavaScript tasks. (JavaScript code is run as discrete tasks in an event loop, aka jobs in a job queue.) alert and its cousins confirm and prompt are archaic stop-the-world functions that completely block the event loop and UI. So although your change to the DOM has been made, the browser hasn't had a chance to render that change visually before the alert stops the world.

    If you really, really need to use alert, do so after a timeout:

    setTimeout(function() {
        alert(/*...*/);
    }, 100);
    

    var x = 0;
    
    function counter() {
      x++;
    
      document.getElementById('aDiv').innerHTML = x;
      setTimeout(function() {
        alert(x);
      }, 100);
    }
    <div id="aDiv">
    0
    </div>
    <input type="button" value="+1" onclick="counter()">

    A delay of 0 is sufficient to give most browsers a chance to do the rendering, but I've generally had to use 100 with Firefox when I've needed to do this. (That may relate only to slightly-older versions of Firefox, though; with the current Firefox I see the DOM change in your snippet even without setTimeout. That's at least newish behavior as I write this in May 2018.)

    0 讨论(0)
  • 2020-12-12 03:01

    Modern browsers are set up such that once they encounter alert() browser will essentially pause the rendering of HTML until the alert() is done.

    0 讨论(0)
  • 2020-12-12 03:14

    The browser do not update the DOM immediately. You can add a delay before calling the alert() function:

    setTimeout(function(){ alert(x) }, 10);
    
    0 讨论(0)
提交回复
热议问题