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
    Feb 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Code Snippet Help

    <script type="text/javascript">
    function countdown (num) {
    for (var i = 0; i <= num; i+=1) {

    setTimeout(function () {
    alert(num-i);
    }, i * 1000);

    }
    }

    countdown(5);

    </script>

    This code snippet keeps returning -1 I don't know why I am new to js learning the tricks please can someone help me

  • #2
    Regular Coder
    Join Date
    Aug 2010
    Posts
    974
    Thanks
    19
    Thanked 212 Times in 210 Posts
    Not exactly sure what you want but,
    see if this helps any ...

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
    
    <title>CountDown</title>
    
    <script type="text/javascript">
    var dspl;
    function countdown (num) {	
    	setTimeout(function () {
    		dspl.innerHTML=num;
    		num -= 1;
    		if(num > 0){
    			countdown (num)
    		}
    		
    	},1000);		
    }
    function init(){
    	dspl = document.getElementById("dspl");
    	countdown(5);
    }
    </script>
    
    
    </head>
    
    <body onload="init()">
      <div id=dspl>    xxxx</div>
    </body>
    </html>

  • #3
    Gütkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    What happens is this:

    1.) The countdown function is called
    2.) A bunch of timeouts are set in a loop
    3.) At the end of the loop, i equals num + 1
    4.) The timeouts start firing. The current values of the variables num and i are still available to the timeout handler because of closures (you might want to look into that). Since the value if i is num + 1, the alert gives you -1.

    You obviously want the timeout handler to remember the value of i at the time the handler is defined. I recently wrote up a few ways to accomplish that in another thread: http://www.codingforums.com/showthre...07#post1057805.

    I'm sure you'll be able to adapt that to your situation.


  •  

    Tags for this Thread

    Posting Permissions

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