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?
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. 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...
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: