SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Zealot ejg's Avatar
    Join Date
    Jun 2007
    Posts
    141
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    functions in functions and setInterval

    I have the following code in test.js:

    Code JavaScript:
    function mytest() {
    	document.write('bbb');
    }
     
    function populate(){
    	lefttime=setInterval('mytest()',10000)
    }
     
    window.onload=populate

    It works fine. bbb is written. I want to put all the code in a function, so in test.js I put:

    Code JavaScript:
    function testFile() {
     
    	   function mytest() {
    	   	   document.write('bbb');
    	   }
     
    	   function populate(){
    	   	   lefttime=setInterval('mytest()',10000)
    	   }
     
    	   window.onload=populate
     
    }
    but now when I call testFile(), I get the error "mytest is not defined".

    This is driving me crazy. Why is wrapping the code in a function causing a problem?

  2. #2
    SitePoint Evangelist
    Join Date
    Jul 2007
    Posts
    345
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try

    lefttime = setInterval(mytest, 10000);

    By using the function name, rather than a string, JavaScript should realise that it needs to keep the function alive rather than throwing it away once it's been parsed.

    This topic is called 'closures'. In this case, a closure lets a nested function maintain a reference to an outer function or variable even when the outer function has finished.


Bookmarks

Posting Permissions

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