Help Me On This Basic Javascript Code

Discussion in 'JavaScript' started by saadi123, Nov 15, 2011.

  1. #1
    Hi,

    I need help on this piece of code. Since I've just started on javascript, I'm unable to resolve even this simple problem. Have a look at the code and then the problem.

    <html>
    <head>
    <script type="text/javascript">
    var i=10;

    function stopwatch()
    {
    document.getElementById("txt").innerHTML=i;
    i=i-1;
    t=setTimeout("stopwatch()", 1000);
    if(i<=0)
    {
    alert("Time's Up");
    }
    return i;
    }

    </script>
    </head>
    <body>
    <input type="button" onclick=stopwatch() value="Stop Watch">
    <div id="txt"></div>
    </body>
    </html>

    Want I want is that the browser displays an alert box after the chronological timer is 0 but this isn't happening. So can you guys explain me the error in this code?
     
    saadi123, Nov 15, 2011 IP
  2. pr0t0n

    pr0t0n Well-Known Member

    Messages:
    243
    Likes Received:
    10
    Best Answers:
    10
    Trophy Points:
    128
    #2
    It does show alert when I test it. Over and over and over, so your counter doesn't stop at 0. How about changing it to something like this:
    
    <script type="text/javascript">
    var i=10;
     
    function stopwatch()
    {
    	document.getElementById("txt").innerHTML=i;
    	if(i<=0)
    	{
    		alert("Time's Up");
    	} else {
    		i=i-1;
    		setTimeout("stopwatch()", 1000);
    	}
    	return i;
    }
    </script>
    
    Code (markup):
     
    pr0t0n, Nov 16, 2011 IP
  3. saadi123

    saadi123 Well-Known Member

    Messages:
    196
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #3
    @pr0t0n.
    Thanks that worked.

    Again my question is that was wrong with my coding. Why it screwed up?
    Secondly, what's the use of the return i; statement? the code's working even without it...
     
    saadi123, Nov 16, 2011 IP
  4. JohnnySchultz

    JohnnySchultz Peon

    Messages:
    277
    Likes Received:
    4
    Best Answers:
    7
    Trophy Points:
    0
    #4
    if found your code that it doesn't stop because you don't clear the timeout call..

    here's my modification based on your code..
    
    
    <script type="text/javascript">
    var i=10;
    
    function stopwatch()
    {
        document.getElementById("txt").innerHTML=i;
        i=i-1;
        t=setTimeout("stopwatch()", 1000);
        if(i <= 0)
        {
            alert("Time's Up");
            clearTimeout(t); // this is the line of code i added
        }
        return i;  // serves no purpose, can be deleted
    }
    
    </script>
    
    HTML:
     
    JohnnySchultz, Nov 17, 2011 IP