Saturday, February 15, 2014

How to use Timer / Stop Watch using JavaScript

In this article I am going to explain timer/stop watch function using JavaScript. In many situations we may get requirement to show the timer in your application. This article will help you to show the timer using JavaScript in a webpage.

To implement the timer first we will write JavaScript function and save it as .Timer.js.

var milliSec = 0;
var seconds = 0;
var minutes = 0; 
function startTimer()
{   
  var timerVal = document.getElementById('lblTimer');   
  timerVal.value = minutes + ":" + seconds + ":" + milliSec;
  go=setTimeout("startTimer()",1);
  milliSec++;
    if(milliSec==100)
    {
      milliSec=0;
      seconds++;
    }
    if(seconds==60)
    {
      seconds=0;
      minutes++;
  }
}

 function stopTimer()
{
  clearTimeout(go)
}

Below is the HTML code to design the webpage. Here you can see that startTimer() and stopTimer fucntion is called on click of the button. Also you can see that I have referred the Timer.js Javascript file which is saved in the root folder.

<html>
  <head>
  <title>Timer Using JavaScript</title>
  <script type="text/javascript" src="Timer.js"></script>
  </head>
  <body>
    <form>
      <table>
      <tr>
          <td colspan="3" ><input id="lblTimer" type="text" name="displayTime" STYLE="color: red; border:0px; font-family: Verdana; font-weight: bold; font-size: 25px; " size="10" maxlength="30 value="00:00:00" /></td>
      </tr>
      <tr>
          <td>
            <input type="button" value="Start Timer" onclick="startTimer()"/>                   
            <input type="button" value="Stop Timer"  onclick="stopTimer()"/>                   
          </td>            
       </tr>               
       </table>
    </form>
  </body>
</html>

The output looks like below.

StopWatch

1 comment:

Ram Kawale said...

Your code helped me lot for for setting a stopwatch for my project, the only thing I found to render the .js filefrom bundlesconfig to .cshtml view page