3

In this snippet, when 'FirstText' is written, then rest of first line is skipped. Then 'SecText' is written on the 2nd line:

<pre>
 <script>
  function text(){
  document.write("FirstText \n SecText");
  }
  text();
 </script>
</pre>

But when I use setInterval() on this function, words are written next to each other (lines are not skipped).

Any suggestions?

Kishore Bandi
  • 5,537
  • 2
  • 31
  • 52
MattMoulson
  • 45
  • 1
  • 1
  • 4

2 Answers2

8

You're seeing \n create a new line because you're inside a <pre /> tag; normally you have to use a <br /> to see a similar new line outside of <pre />.

When you call document.write before the page has finished loaded, the output is entered inplace; so you'll see your FirstText \n SecText written within the <pre />.

However, when it's called after the page has loaded (within setInterval), the existing page is cleared before the result is written; hence <pre /> is being removed, and you're not seeing your new line any more.

As you're not closing the document using document.close(), successive calls to document.write in your setInterval are adding to the document stream opened by the first iteration of setInterval.

You can fix this by using a <br /> rather than \n;

     <script>
      function text(){
      document.write("FirstText <br /> SecText <br />");
      }

      setInterval(text, 1000);
     </script>

For more info, see https://developer.mozilla.org/en-US/docs/Web/API/document.write and document.write clears page

Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180
2

try this:

document.write("FirstText <br /> SecText <br/>");

working example:

http://jsbin.com/oyolod/4/

BeNdErR
  • 17,471
  • 21
  • 72
  • 103