0

I created a simple loop that fills up the screen with emojis. This worked fine, however I tried adding a small delay before rendering each subsequent emoji and after the initial delay there is a weird behaviour where everything above the opening <body> tag is replaced with the following:

<html>
  <head></head>
<body>
  <div style="left: 25px; top: 5px;"></div>
  <div style="left: 45px; top: 5px;"></div>
...etc

Before this, I have styles, title, meta tags, the initial <!DOCTYPE html> tag, etc. The code I'm using is:

<!DOCTYPE html>
<html lang="en">
<head>
... etc ...
</head>
<body>
    <script>
        function delay(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }
    
        async function load() {
            // Below snippet works standalone, as intended, without "await delay(1000);"
            for (let y = 5; y < screen.height - 20; y = y + 20) {
                for (let i = 5; i < screen.width - 20; i = i + 20) {
                    document.writeln('<div style="left: ' + i + 'px; top: ' + y + 'px;"></div>');
                    await delay(1000); // Code gets replaced after this line runs the first time.
                }
            } // End snippet      
        }
    
        load();
    </script>
</body>

I'm doing this as an exercise to learn JavaScript, so there is probably something obvious I'm doing wrong, however I couldn't find any results for the header information being replaced.

Thanks for taking the time to read this far.

Ayleanna
  • 193
  • 1
  • 3
  • 9
  • 2
    document.writeln is the wrong tool for this job. You want to create an element and append it to the page – async await Apr 18 '22 at 21:19
  • 1
    When `document.write()` and `document.writeln()` are called after the DOM has loaded, they implicitly call `document.open()`, which means that they create a new document for their content (which wipes out the old document). These are legacy methods that really don't have much practical use today. – Scott Marcus Apr 18 '22 at 21:23
  • Well the egg is certainly on my face. Thank you so much! – Ayleanna Apr 18 '22 at 21:24
  • 1
    @tomofv if you're curious about using `document.createElement` to solve this, I'll leave some code [here](https://cl1p.net/some-code) – async await Apr 18 '22 at 21:29
  • That's really highlighted how unfamiliar I am with JavaScript haha. Thank you for taking the time to demonstrate that! Really appreciate it. :) – Ayleanna Apr 18 '22 at 21:48

0 Answers0