I've read the following topic is-javascript-guaranteed-to-be-single-threaded There is the good example there:
<textarea id="log" rows="20" cols="40"></textarea>
<input id="inp">
<script type="text/javascript">
var l= document.getElementById('log');
var i= document.getElementById('inp');
i.onblur= function() {
l.value+= 'blur\n';
};
setTimeout(function() {
l.value+= 'log in\n';
l.focus();
l.value+= 'log out\n';
}, 100);
i.focus();
</script>
The output is
log in
blur
log out
instead of expected
log in
log out
blur
So this basically shows that my event handler on blur
was triggered which interrupted the execution of the code within setTimeout callback. I've read couple of other articles and explanations stating that code will not be interrupted (run-to-completion principle) except for some corner cases like modal popups (alert, prompt windows). So why is it interrupted in the example case?
The only explanation I can come with is that I manually trigger focus
event from the code and at the same time the control of the execution is on JS engine. If not triggered manually the blur event during execution of code would be detected by browser and put into the queue which will be processed only after the execution of code is complete (the stack is empty).