ChipChamp007 Posted January 28, 2007 Share Posted January 28, 2007 Okay, I'm using the example on W3Schools for making a timer, and it works fine. The only problem is that if I were to click the start button again and again it starts counting quicker and quicker. How can I make it so that when I click on it again it restarts at 0, and doesn't get any faster?EDIT: Could somebody please move this to the JavaScript section? Sorry! Link to comment Share on other sites More sharing options...
jesh Posted January 29, 2007 Share Posted January 29, 2007 Can you post the code that you already have? Link to comment Share on other sites More sharing options...
ChipChamp007 Posted January 29, 2007 Author Share Posted January 29, 2007 Okay... well the problem happens on this code: (Directly from tutorial) <html><head><script type="text/javascript">var c=0var tfunction timedCount(){document.getElementById('txt').value=cc=c+1t=setTimeout("timedCount()",1000)}</script></head><body><form><input type="button" value="Start count!" onClick="timedCount()"><input type="text" id="txt"></form><p>Click on the button above. The input field will count for ever, starting at 0.</p></body></html> Link to comment Share on other sites More sharing options...
jesh Posted January 29, 2007 Share Posted January 29, 2007 Ah, each time you click the button, a new timer starts. So, if you click the button three times, there will be three timers, each of which will be increasing your c variable by one. This would explain why you are seeing the counter speed up when you click the button multiple times. You'll need to have a separate function that happens when a user clicks on the button. This function will stop any timers that happen to be running and will reset the counter to 0.Perhaps something like this will help: <html><head><script type="text/javascript">var c = 0;var t;function startTimer(){ // first step, if there is a timeout happening, let's clear it. if (t) { clearTimeout(t); } // second step, let's reset the counter to 0 c = 0; // finally, let's start the timer timedCount();}function timedCount(){ document.getElementById('txt').value = c; c++; // this is the same as c=c+1 t = setTimeout("timedCount()",1000);}</script></head><body><form><input type="button" value="Start count!" onClick="startTimer()"><input type="text" id="txt"></form><p>Click on the button above. The input field will count for ever, starting at 0.</p></body></html> Link to comment Share on other sites More sharing options...
ChipChamp007 Posted January 30, 2007 Author Share Posted January 30, 2007 Thanks! That worked! And very clear. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now