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.
var x = 0;
function counter() {
x++;
document.getElementById('aDiv').innerHTML = x;
alert(x);
}
<div id="aDiv">
0
</div>
<input type="button" value="+1" onclick="counter()">
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.)
The browser do not update the DOM immediately. You can add a delay before calling the alert() function:
setTimeout(function(){ alert(x) }, 10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With