Connecting Tech Pros Worldwide Forums | Help | Site Map

settimeout problem...

Newbie
 
Join Date: Nov 2006
Posts: 1
#1: Nov 16 '06
Hello,

I have a problem with settimeout.
When I call the initCountDown method on body's onLoad event. If I call the initCountDown on body's load, the button's code works fine afterwards.

However, if I do not place initcountDown in body's load, the button calls countDown method only once and settimeout does not function.

Any help or tips would be greatly appreciated.
Thanks

*********************************************
Expand|Select|Wrap|Line Numbers
  1. <SCRIPT language="JavaScript">
  2. var secs;
  3. var timeout;
  4. function initCountDown(init) {
  5.     secs = init;
  6.     countDown();
  7. }
  8.  
  9. function countDown () {
  10.     if (secs >= 0) {
  11.         self.status = secs;
  12.         secs = secs - 1 ;
  13.         timeout = setTimeout(function(){countDown();}, 1000);
  14.     }  else {
  15.         clearTimeout(timeout);    
  16.     }
  17. }
  18. </SCRIPT>
  19.  
  20. <body onload="initCountDown(10)">
  21. <form>
  22. <INPUT type=submit id=btnCount value="Count Down" onClick = "initCountDown(10)">
  23. </form>
  24. </body>

gits's Avatar
Moderator
 
Join Date: May 2007
Location: Munich, Germany
Posts: 4,136
#2: May 8 '08

re: settimeout problem...


just add a return false; to the js-call for the button's onclick, otherwise the form is submitted (since your button is a submit-button) and the page reloaded:

Expand|Select|Wrap|Line Numbers
  1. <input type="submit" value="Count Down" onClick = "initCountDown(10); return false;">
  2.  
another option would be to use type="button" for the button :) and submit the form through javascripts submit() method.

kind regards
Reply


Similar JavaScript / Ajax / DHTML bytes