0

I have tested this code on firefox and it only gets up to "pat2". IE is the same. In Chrome it runs fine and runs indefinitely.

Is it obvious as to why this is the case? Firebug does not show any errors and the loading icon keeps showing it is working on something.

<script type="text/javascript">
i = 1
function writeurl(){
document.write("pat"+i+"<br>")
i+=1
setTimeout(writeurl,1000)
}
writeurl()
</script>

If it only ran once, perhaps I could attribute it to something I did wrong, but it runs twice then "stops" without error.

Also it may help to know that the following works fine and it keeps running until the callstack overflows. ;)

<script type="text/javascript">
i = 1
function writeurl(){
document.write("pat"+i+"<br>")
i+=1
writeurl()
}
writeurl()
</script>
wisling
  • 45
  • 7

1 Answers1

1

The problem here is actually with the document.write call rather than the setTimeout call. If you use console.log(i) you'll see the code work in IE, Firefox, Chrome. You can inspect the log output in the developer tools console (see here) For example:

<script type="text/javascript">
  var i = 1;
  function writeurl(){
    console.log(i);
    i+=1
    setTimeout(writeurl, 1000);
  }
  writeurl();
</script>

The problem is that after the document is loaded, document.write overwrites content (see this question for more).

Rather than using document.write, try using the following:

var i = 1;
function writeurl(){
  var div =  document.createElement("div");
  var text = document.createTextNode("pat " + i);
  div.appendChild(text);
  document.body.appendChild(div);
  i+=1;
  setTimeout(writeurl,1000);
}
writeurl();

Here's an example on codepen. You can also use JQuery to make this code much more concise. I've added an example using JQuery in the codepen as well.

Community
  • 1
  • 1
Julia Schwarz
  • 2,610
  • 1
  • 19
  • 25
  • I see what you mean. This is definitely a better way than using document.write() Perhaps firefox and IE have safeguards against continually overwriting reloading a new webpage created using document.write. Thanks! – wisling Aug 07 '14 at 03:28