KOOLz KOOLz - 12 days ago 6
Javascript Question

Javascript setinterval's time not working

The following code in:

<script type="text/javascript">

function a() {
document.write("bob ");
}

setInterval("a()", 1000);

</script>


is to supposed to have an out put of 1
bob
,
printed
on the browser,
every second
.

I am using firefox, and it only prints onces, and nothing....
anyone has any ideas why? mauybe I'm missing something?
ec = now.getSeconds();
document.write(hours+':'+mins+':'+sec+"
");
}

UPDATE EDIT:


I have the same problem with this code:

<script type="text/javascript">
function printtime () {
var now = new Date();
var hours = now.getHours();
var mins = now.getMinutes();
var sec = now.getSeconds();
document.write(hours+':'+mins+':'+sec+"<br />");
}

setInterval("printtime()", 1000);
</script>


It's supposed to print the time on the browser under the previous one, once per second.... but it wont print further than the first..

Answer

Using document.write after the main HTML parsing is complete wipes out the page entirely and replaces it with what you output. On Firefox, that wipes out your timer, so it stops after firing just once and wiping the page. (This is not true of Chrome, which keeps the a function around, so your original code works on Chrome, but not Firefox.)

If you just output, say, new elements to the page, what you have works:

function a() {
  var p = document.createElement("p");
  p.appendChild(
    document.createTextNode("bob")
  );
  document.body.appendChild(p);
}

setInterval("a()", 1000);

but, it's best not to use strings with setInterval or setTimeout; just refer to the function instead:

setInterval(a, 1000);

function a() {
  var p = document.createElement("p");
  p.appendChild(
    document.createTextNode("bob")
  );
  document.body.appendChild(p);
}

setInterval(a, 1000);

Or if you want to just add text to the end of an existing element repeatedly:

function a() {
  var p = document.getElementById("target");
  p.appendChild(
    document.createTextNode("bob ")
  );
}

setInterval(a, 1000);
<p id="target"></p>

Comments