I've always thought that, since JavaScript was single-threaded, I could attach event handlers without worrying about the handlers getting executed while I was in the middle of executing code. To my surprise, I found that they could. According to this answer, the 'Unresponsive Script' dialog box can cause events to be raised while the script is still running.
I tested this with the following code:
<script>
function loop() {
var cond;
onblur = function (event) {
cond = false;
};
cond = true;
while (cond)
;
alert('loop exited!');
}
</script>
<button onclick="loop()">loop()</button>
In Firefox 11.0, the function prints "loop exited" after clicking continue. The loop seems to be paused, with events allowed to execute. This is akin to a Unix signal, which temporarily changes the context of the target thread. But it is much more dangerous, as it allows external state to be altered.
Is this a bug? Should I no longer depend on the single-flow-of-execution model of JavaScript and ensure that all my scripts are re-entrant? Or is it a flaw not worth pursuing despite a major browser allowing this to happen?