user7102066
user7102066

Reputation:

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..

Upvotes: 0

Views: 84

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1075735

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>

Upvotes: 5

Feathercrown
Feathercrown

Reputation: 2591

Here you go; don't add quotes or parenthesis after your function in setInterval();.

<script type="text/javascript">

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

setInterval(a, 1000);

</script>

Also worth noting is document.write(); will delete a loaded webpage, including yours.

Upvotes: 1

Mahi
Mahi

Reputation: 1727

function a() {
    console.log("bob ");
}

setInterval(a, 1000);
*{ background-color: yellow; }

Upvotes: 2

Related Questions