Web Analytics Made Easy -
StatCounter 2 noobie functions - CodingForum

Announcement

Collapse
No announcement yet.

2 noobie functions

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • 2 noobie functions

    hey , i got 2 function , the one working and the other one is'nt

    heres the functions :

    Code:
                            var toDisplay = "f";
    			function human(){
    				var toAdd = toDisplay.substring(0,1);
    				setTimeout(human , 500);
    				document.getElementById('box').innerHTML += toAdd;
    			}
    			human(); // works (display "f" every half a sec)
    			
    			function human2(toDisplay2){
    				var toAdd = toDisplay2.substring(0,1);
    				var t = setTimeout("human2(toDisplay2)" , 500);
    				document.getElementById('box').innerHTML += toAdd;
    			}
    			human2("dsd"); // not working (only display "d" and stop)
    the first function works ( keep printing "f" every 0.5 sec )
    the second function only work once and than stop ( print "d" and than stop )

    what's the problem with the second function?

    thanks , Mor.

  • #2
    That's because when the timeout fires, the code tries to execute *exactly* what you gave there, in the setTimeout:
    Code:
        human2(toDisplay2)
    But by that time, the variable toDisplay2 no longer exists, so you get an error.

    You have to code that this way:
    Code:
    	function human2(toDisplay2){
    		var toAdd = toDisplay2.substring(0,1);
    		setTimeout("human2('" + toDisplay2 + "')" , 500);
    		document.getElementById('box').innerHTML += toAdd;
    	}
    	human2("dsd");
    No point in assigning the setTimeout to the variable t because that variable, also, disappears as soon as the human2 function finishes.

    p.s.: You can, of course, reverse the quotes and apostrophes. Makes no difference.
    Code:
    		setTimeout('human2("' + toDisplay2 + '")' , 500);
    Be yourself. No one else is as qualified.

    Comment


    • #3
      Here is another way ...

      Code:
      <body>
      <div id="box"> </div>
      </body>
      <script>
      function human2(toDisplay2){
            (function inner(){	
      	var toAdd = toDisplay2.substring(0,1);
      	setTimeout(inner , 500);
      	document.getElementById('box').innerHTML += toAdd;})()
      			}
      			human2("dsd"); 
      </script>
      this way toDisplay2 continues to exist.
      Last edited by DaveyErwin; Sep 7, 2011, 10:00 PM.

      Comment


      • #4
        In case you get tired of seeing the d's go by ...

        Code:
        <body>
        <div id="box"> </div>
        <input type="button" value="stop!" onclick = "clearTimeout(t)">
        </body>
        <script>
        function human2(toDisplay2){
           (function inner(){	
        	var toAdd = toDisplay2.substring(0,1);
        	t = setTimeout(inner , 500);
        	document.getElementById('box').innerHTML += toAdd;})()
        			}
        			human2("dsd"); 
        </script>

        Comment


        • #5
          And not to quibble--because Davey's code works--I would always add in var t = null; outside of any function both to ensure that the variable really *is* global and to give myself a convenient way to test to see if any timeout is active.
          Code:
          <body>
          <div id="box"> </div>
          <input type="button" value="stop!" onclick = "if ( t != null ) { clearTimeout(t); t = null; }">
          </body>
          <script>
          var t = null;
          function human2(toDisplay2){
             (function inner(){	
          	var toAdd = toDisplay2.substring(0,1);
          	t = setTimeout(inner , 500);
          	document.getElementById('box').innerHTML += toAdd;})()
          			}
          			human2("dsd"); 
          </script>
          My code there adds nothing at all to the functionality in this particular example. But that technique can be useful in other circumstances.
          Be yourself. No one else is as qualified.

          Comment


          • #6
            I feel the need to clear things up a bit, since the replies are a bit beside the point.

            Originally posted by Old Pedant View Post
            You have to code that this way:
            Code:
            	function human2(toDisplay2){
            		var toAdd = toDisplay2.substring(0,1);
            		setTimeout("human2('" + toDisplay2 + "')" , 500);
            		document.getElementById('box').innerHTML += toAdd;
            	}
            	human2("dsd");
            The main problem with the original code is that it puts code into a string, instead of a function (which would create a closure, and all would be fine). While this approach here does work, it isn't really a solution; suppose the function human2 doesn't expect a string parameter but an array or an object — now what are you going to do? Convert the parameter to a JSON string in order to be able to put it into the code string? That's just silly.

            Generally speaking — never put code into a string. If you do, you're entering a world of hurt (and undebuggability).


            Originally posted by DaveyErwin View Post
            Here is another way ...

            Code:
            <body>
            <div id="box"> </div>
            </body>
            <script>
            function human2(toDisplay2){
                  (function inner(){	
            	var toAdd = toDisplay2.substring(0,1);
            	setTimeout(inner , 500);
            	document.getElementById('box').innerHTML += toAdd;})()
            			}
            			human2("dsd"); 
            </script>
            this way toDisplay2 continues to exist.
            That's the right idea, but it's a bit convoluted and makes the whole closure thing look more complicated than it really is.

            Creating a closure in order to pass that local variable as a parameter is as easy as this:
            PHP Code:
            function human2(toDisplay2) {
                var 
            toAdd toDisplay2.substring(0,1);
                
            document.getElementById('box').innerHTML += toAdd;
                
            setTimeout(function () {human2(toDisplay2);} , 500);

            There's no need for a named inner function.
            .My new Javascript tutorial site: http://reallifejs.com/
            .Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
            .Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback

            Comment

            Working...
            X
            😀
            🥰
            🤢
            😎
            😡
            👍
            👎