Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Sep 2006
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy New to javascript (need help with simple script)

    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?

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

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,462
    Thanks
    0
    Thanked 633 Times in 623 Posts
    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.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #3
    Supreme Master coder! _Aerospace_Eng_'s Avatar
    Join Date
    Dec 2004
    Location
    In a place far, far away...
    Posts
    19,291
    Thanks
    2
    Thanked 1,043 Times in 1,019 Posts
    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.
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <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
    </script>
    </head>
    
    <body>
    <div id="holdcount">&nbsp;</div>
    </body>
    </html>
    ||||If you are getting paid to do a job, don't ask for help on it!||||


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •