I came across some code that uses setTimeout
to make sure that a callback is executed after the document has been parsed.
For example:
<!DOCTYPE html>
<html>
<head>
<script>
setTimeout(() => console.log(document.readyState));
</script>
</head>
<body>
<!-- lots of HTML to parse, which will take a long time -->
</body>
</html>
Here the HTML is parsed first and then the document readyState of complete
is logged in the console.
My guess is that the parsing appears in the call stack before the callback or something like that, but I don't understand how this works. I expected that there would be a race between the parsing and the callback to finish first.
Why is the callback executed after the document has been parsed?