Showing posts with label setTimeout(). Show all posts
Showing posts with label setTimeout(). Show all posts

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>

JavaScript : Clock Example

To following this step, you should know about "setTimeout()" methods and JavaScript DateTime objects. "setTimeout()" is look like recursive function (recursion) that allowed add delay before it action. "setTimeout()" is required Method's name that you want to repeat and delay time (millisecond).

Syntax
   setTimeout("MethodName()","DelayTime")


Example Clock
This example used to create interactive clock on your webpage by using setTimeout() and show output on <div id="divOutput">. You can move this tag everywhere to show your clock on your webpage.


<script language="JavaScript">
   function callTime() {
      var d = new Date();
      var result = d.getDate()+"/";
      result += (d.getMonth()+1)+"/";
      result += d.getYear() + " ";
      result += d.getHours() + ":"
      result += d.getMinutes() + ":";
      result += d.getSeconds();


      document.getElementById("divOutput").innerHTML = result;
      setTimeout("callTime()", 1000);
}
</script>


<body onload="callTime();">
<div id="divOutput"> </div>
</body>
##############################


Related Posts Plugin for WordPress, Blogger...