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

后端 未结 3 1771
感动是毒
感动是毒 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);
    }
    0

    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.)

提交回复
热议问题