The reason is the function, as a whole, is executing synchronously. By the time you set the output to wait for it...
, it enters the long-running loop and hog the thread. If you wrap the rest in a timeout
, the first text will appear as normal.
var output = document.getElementById('output');
document.getElementById('go').onclick = function() {
output.textContent += 'wait for it...';
window.setTimeout(function() {
for (var i=0; i<3000000000; i++) {
var unused = i; // don't really care
}
output.textContent += ' dary!';
}, 0);
};
Note that it will still freeze the UI while processing.
Edit: Using 0
as the delay value in Chrome works, but it does not in latest Firefox and IE 10. Changing the value to 10
works in both cases.