0

The following code waits 2 seconds then prints some hello worlds.

<!DOCTYPE html>
<html>
<body onload="myTimedFunction()">

<script>
    function myTimedFunction() {
        setTimeout(function() { document.write("hello world");document.write(" hello world2");runMe();}, 2000); 
    }
    function runMe(){document.write(" hello world3");}
</script>
<br>
<p>This text will disappear when the script runs</p>

</body>
</html>

like it says in the p tag the text disapears after the script has run. Furthermore, the webpage shows "Connecting..." with a loading symbol next to it when the script runs; this goes away when I hit escape. Why does the text disappear? Why is the javascript not stopping until I hit escape, missing semicolon? I am using firefox, in chrome the "Connecting..." never comes up, but the text still vanishes. Thank you for reading.

Hugo Riggs
  • 55
  • 7

3 Answers3

1

If the current document is still “open”, i.e. it’s still being parsed, document.write will insert its argument string at the current position in the document. When the page has finished parsing, though, as it is after onload (and a two-second timeout), it’s closed; document.write will reopen it, which has the effect of removing all current content.

Create a text node and append it to <body> instead!

function myTimedFunction() {
    setTimeout(function () {
        var textNode = document.createTextNode('hello world');

        document.body.appendChild(textNode);
    }, 2000); 
}
Ry-
  • 199,309
  • 51
  • 404
  • 420
0

This problem doesn't have anything to do with setTimeout. This usually happens when using document.write.

Simply replace your document.write with something like:

document.querySelector('body>p').innerHTML += 'hello world';

If you look it up, you will see that document.write is considered a bad practice, check this post out for reasons but in your case the main reason is:

document.write executed after the page has finished loading will overwrite the page, or write a new page, or not work

Community
  • 1
  • 1
Mehran Hatami
  • 11,801
  • 5
  • 26
  • 32
0

You can try following code:

<!DOCTYPE html>
<html>
<body onload="myTimedFunction()">


<br>
<p>This text will disappear when the script runs</p>

</body>
</html>

<script>
    function myTimedFunction() {
       setTimeout(function() { document.write(document.body.innerHTML+"hello world");document.write(" hello world2");runMe();}, 2000); 
    }
    function runMe(){document.write(" hello world3");}
</script>
suyog patil
  • 409
  • 3
  • 13