View Full Version : New to javascript (need help with simple script)

09-05-2006, 11:46 PM
Ok well as one of my projects I just want to make a simple counter so I started but seem to be stuck. When the page loads it stays at 0 and wont increase the number every time it loops through the function. Does anyone know how I can fix this?

var count = 0;


function doTimer()
document.write(count); //writes out number
count += 1; //add 1 to count
setTimeout("doTimer();", 5000); //call doTimer after 5 seconds

09-06-2006, 12:26 AM
You need to get rid of the document.write statement as the first time that runs after the page has loaded it will overwrite the entire page. You should use innerHTML or the Document Object Model to update an existing page.

09-06-2006, 12:33 AM
Your problem is because you are using document.write. Once you call the function just once the whole page gets written with the 0. The count++ and setTimeout never occur.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript">
var count = 0; // intitialize count to 0
function doTimer()
document.getElementById('holdcount').firstChild.nodeValue = count; // changes text in div with id="holdcount" to current count
count++; // increases count by 1 each time function is called
window.setTimeout("doTimer()", 5000); //call doTimer after 5 seconds
window.onload = doTimer; // div with id="holdcount" needs to exist before we can call the function

<div id="holdcount">&nbsp;</div>