-2

I first did this:

<script>
    function result2() {
        document.write("...");
    }
    function result1() {
        document.write("..");
        setTimeout(result2, 1000);
    }
    document.write(".");
    setTimeout(result1, 1000);
</script>
<div id="body"></div>

setTimeout() doesn't work at all ninety-nine times out of a hundred, so I was surprised to see it working, even if it glitched at the very end. But it didn't work like I used to want, so I re-wrote the script just a little bit to be something like that:

<script>
    function result2() {
        document.getElementById("body").innerHTML = "...";
    }
    function result1() {
        document.getElementById("body").innerHTML = "..";
        setTimeout(result2, 1000);
    }
    document.getElementById("body").innerHTML = ".";
    setTimeout(result1, 1000);
</script>
<div id="body"></div>

But nothing happened at all, it just gave me a blank page... So I tried setInterval(), but here again, it didn't work. So please, help me, how can I solve this problem?

bexandre
  • 113
  • 1
  • 4

2 Answers2

2

The problem is when the code is executed, the elements are not available in the DOM. You can use any one of the below solution

  1. Move the <script> at the end of <body so, when the code is run, the elements are available in the DOM
  2. Wrap the code that access DOM elements in DOMContentLoaded event callback

<script>
    function result2() {
        document.getElementById("body").innerHTML = "...";
    }

    function result1() {
        document.getElementById("body").innerHTML = "..";
        setInterval(result2, 1000);
    }

    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById("body").innerHTML = ".";
        setInterval(result1, 1000);
    });

</script>
<div id="body"></div>
Tushar
  • 85,780
  • 21
  • 159
  • 179
0

Add your script at the end of body tag and it should work

function result2() {
   document.getElementById("body").innerHTML = "...";
    }

function result1() {
    document.getElementById("body").innerHTML = "..";
        setInterval(result2, 1000);
    }

 document.getElementById("body").innerHTML = ".";
    setInterval(result1, 1000);
<div id="body"></div>