Nuffnang Ads

Thursday, 4 September 2014

Stopwatch using Javascript - part 2 (reset button)

This post will show you how to add reset button at the stopwatch.

1) Follow the steps at the previous post to get the simple stopwatch source code here

2) Add a "reset" button after the "stop" button, and at the onClick, put a new function name to do the resetting, for example :-

<input type = "button" name = "Reset" value = "Reset" onClick = "fnreset()">

3) Create a reset function, for example:-

function fnreset()
{
msec=0;
sec=0;
min=0;
document.form1.txt1.value=min+" : "+sec+" : "+msec;
}

4) Save and Run, click Start, Stop and then Reset.

Start and Stop

Reset

5) Here are the full codes:-

<html>
<head>
<script language = "javascript">
var msec=0,sec=0,min=0;
function fnWatch()
{
msec++;
if(msec==100)
{
 msec=0;
 sec++;
 if(sec==59)
 {
  sec=0;
  min++;
  if(min==59)
  {min=0;
  }
 }
}
ID = window.setTimeout("fnWatch();",10);

  document.form1.txt1.value=min+" : "+sec+" : "+msec;
}
function fnreset()
{
msec=0;
sec=0;
min=0;
document.form1.txt1.value=min+" : "+sec+" : "+msec;
}
</script>
</head>
<body>
 <form name = "form1">
  <h1>Javascript stopwatch</h1>
  <input type = "text" name = "txt1">
  <br/><br/>
  <input type = "button" name = "Start" value = "Start" onClick = "fnWatch()">
  <input type = "button" name = "Stop" value = "Stop" onClick = "window.clearTimeout(ID)">
  <input type = "button" name = "Reset" value = "Reset" onClick = "fnreset()">
 </form>

</body>
</html>


6) Done

No comments:

Post a Comment