say I have code like this
<html><body>
<bunch of html tags...>
<script>
function myF()={};
setTimeout(myF, 100);
</script>
<lots of more html goes here.....></body></html>
As I understand it, the script will be evaluated as the html is parsed. But, in this case we have a setTimeout followed by lots of html parsing. When will the timeout get to make its call? Does it need to wait until all the html parsing is done before myF is finally called, or will myF be called when the timeout event occurs, even if there is more html parsing to accomplish?
No, setTimeout() does not necessarily wait for DOMContentLoaded
If it did, we wouldn't have need for the
DOMContentLoaded
event, but if that's not enough to convince you, below is conclusive evidence:If it had to wait for
DOMContentLoaded
, you'd seeHowever (at least for me), a good portion of the time, the output is
Even though the parsing of HTML is single-threaded, it is blocked when
<script>
withoutasync
and<link>
must pause to fetch the resource from the URL and execute the script or stylesheet respectively, which means there's a race-condition between theDOMContentLoaded
event andsetTimeout(function() { ... }, 15)
.Don't rely on that.
setTimeout
doesn't create an 'interrupt' so to speak, all it does it add the function to a queue that is checked when the browser decides to check it. This could be at the end of the thread loop, or it could be during HTML parsing.Further reading on JavaScript timers: https://johnresig.com/blog/how-javascript-timers-work/
The better (standard) way to wait until the HTML is finished parsing is like this:
Or, using jQuery, like this: