Simple question.
What's so special about the DOM that manipulating it is blocked by long-running javascript functions invoked after the DOM manipulation calls? Here's an example:
function notify(msg) {
var div = document.createElement("div");
div.textContent = msg;
document.body.appendChild(div);
}
// long-running func
function block() {
var iter = 3e8;
while (iter--)
Math.sqrt(iter);
notify("block() done!");
}
document.body.onclick = function(){
notify("click event!");
block();
};
both, click event! and block() done! appear simultaneously after the long-running function exits rather than click event! triggering immediately and block() done! appearing later.
here's a demo: http://jsfiddle.net/bxuNb/1/
if notify("click event!"); is replaced with alert("click event!");, then it responds instantly. what's going on here?
thanks!
What's so special about the DOM that manipulating it is blocked by javascript functions
It's optimized. Your screen won't be repainted after every single interaction with the DOM.
…invoked after the DOM manipulation calls
It can't be known that there is no further DOM manipulation ahead in the execution - therefore it doesn't update your screen right away. Even while that would be possible by static code analysis, there is another DOM manipulation in your example. The interpreter just can't know that the few lines of code in between will take that long to execute.
If you want to allow the screen to update in between, start the long-running block with a timeout after your first output:
document.body.onclick = function(){
notify("click event!");
setTimeout(block, 0);
};