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.
The browser do not update the DOM immediately. You can add a delay before calling the alert() function:
setTimeout(function(){ alert(x) }, 10);