I can't find anywhere on stack overflow or the internet a detailed guide to how javascript chooses its order of executing statements.
I have the following code. When I attach the debugger in the browser is appears to execute in order.
var cvs = document.getElementById('cvs');
cvs.width = window.innerWidth;
cvs.height = window.innerHeight;
var w = window;
w.onresize = (event) => {
cvs.width = window.innerWidth;
cvs.height = window.innerHeight;
};
However, the following bizarre behavior happens: the lines that begin with cvs.width
execute just fine. However the line that begins with w.onresize
doesn't work because w
is null. However I can inspect the line var w = window;
which executes prior, and I can see that both w and window are NOT null. So how is it that both w and window are not null, until the next line, at which time they are???
NOTE: People are responding about asynchronous execution. There's nothing asynchronous. The event handler is never attached in the first place, because w
or window
or null. This is not a concurrency problem, it's some type of script execution order and/or scoping problem.
The problem seems to be related to putting the script tag in the wrong place in the html? Here was my HTML:
html:
<html>
<head></head>
<body>
<div>
<script src="bundle.js" />
</div>
</body>
</html>
Moving the script out of the div changed the behavior of the "shroedinger's window".