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 Coder
    Join Date
    Jun 2004
    Posts
    51
    Thanks
    0
    Thanked 0 Times in 0 Posts

    problem with setTimeout()

    Hello.

    Can anyone see why this simple script will not loop as it's supposed to?

    Code:
    <html>
    <head>
    <script>
    function depart() {
    today = new Date();
    leave = new Date(2004, 12, 18, 13, 30, 00, 0);
    difference = leave.getTime() - today.getTime();
    document.write ("<h1>" + difference + "</h1>");
    
    setTimeout ("depart()", 1000);
    }
    </script>
    </head>
    <body onload="depart();">
    </body>
    </html>
    The debugger in firefox says "depart is not defined"

  • #2
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,075
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Because when you document.write after the page has loaded, the current page will be overwritten by the new string. So the next time depart() is called, it is not there anymore because the page is already replaced. Use innerHTML or DOM to display the string without replacing the whole page.
    Code:
    <html>
    <head>
    <script>
    function depart() {
      var today = new Date();
      var leave = new Date(2004, 12, 18, 13, 30, 00, 0);
      var difference = leave.getTime() - today.getTime();
      document.getElementById("diff").innerHTML =  difference;
      setTimeout ("depart()", 1000);
    }
    </script>
    </head>
    <body onload="depart();">
    <h1 id="diff"></h1>
    </body>
    </html>
    Last edited by glenngv; 12-11-2004 at 08:58 AM.
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #3
    New Coder
    Join Date
    Jun 2004
    Posts
    51
    Thanks
    0
    Thanked 0 Times in 0 Posts
    That's great - A clear explanation and a solution to the problem. Thanks glenngv


  •  

    Posting Permissions

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