JavaScript : Countdown Example

To following this step, you should know about "setTimeout()", if statement and JavaScript Object first. This example will create an Countdown timer that you can set minutes and seconds by yourself. You can start or stop Countdown or Timing event anytime by using "clearTimeout()". 

Syntax clearTimeout()
variableName setTimeout("MethodName", DelayTime);
clearTimeout(variableName);

Example Countdown 

<script language="JavaScript">
var c=0, t, timeon=0;


function CountDown() {
   if(c > 0) {
      m = parseInt(c / 60);
      s = parseInt(c % 60);
      res = (m < 10 ? "0"+m : m) + ":" + (s < 10 ? "0"+s : s);
      document.getElementById("txt").value = res;
      c = c - 1;
      t = setTimeout("CountDown()",1000);
   }
   else {
      stopCount();
      c = 0;
      document.getElementById('txt').value = "Time Up !!";
   }
}
function doTimer() {
   if (!timeon) {
      timeon = 1;
      if(c == 0) {
         m = parseInt(document.getElementById("txtM").value);
         s = parseInt(document.getElementById("txtS").value);
         c = parseInt(m * 60) + parseInt(s);
      }
      CountDown();
   }
}
function stopCount() {
   clearTimeout(t);
   timeon = 0;
}
function ClearTime() {
   c = 0;
   document.getElementById('txt').value = "";
}
</script>

<form> Set Min : <input type="text" id="txtM" value="0"> <br>
Set Sec : <input type="text" id="txtS" value="0"> <br>
<input type="button" value="Start" onclick="doTimer()">
<input type="text" id="txt">
<input type="button" value="Stop" onclick="stopCount()">
<input type="button" value="Clear" onclick="ClearTime()">
</form>

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...