Summary
I'm writing code with a lot of alerts/confirms and I'm finding it a pain to keep everything rendering the way it should. I just want the snippet below to work as expected. First "Before" should be displayed, then it should wait for the user to confirm the alert box. Then "After" should be displayed.
document.getElementById('display').innerHTML = "Before";
// ALERT
document.getElementById('display').innerHTML = "After";
Tried
I've tried the naive way & the way recommended on a million dupes all over SO with setTimeout()
. (I tried zero & non-zero time
.)
document.getElementById('display').innerHTML = "Before";
alert("Alert Text")
document.getElementById('display').innerHTML = "After";
document.getElementById('display').innerHTML = "Before";
setTimeout(function() {
alert("Alert Text")
}, time);
document.getElementById('display').innerHTML = "After";
In the first case, the stuff before hasn't finished rendering, before alert halts execution. And in the second, the stuff below has already begun rendering, replacing the stuff above.
Ideas
One can put everthing below the alert within the setTimeout()
block. Not a terrible hack for one alert. But with lots of alerts, that means lots of nested setTimeout()
, which seems wrong on several levels!
A simple sleep()
would resolve everything. But the accepted SO answer warns never to use sleep()
equivalents in JS, preferring setTimeout()
instead. So back to square 1!
TL;DR: What's the best way to use alert()
so that the HTML before & after are rendered in order?