Introduction:
How will you count the time of timer up to infinite, and how to stop that time in java script? To find the answer of these questions learn this article. Here we will use two functions one is timedcount() for counting the time up to infinite and another is stopcount() for stop the time.
There are two methods used in JavaScript.
- setTimeout ()
- clearTimeout ()
Example:
<html>
<head>
<title>TimeCount and StopCount</title>
</head>
<script type="text/javascript">
var a=0
var x
function timedCount()
{
document.getElementById('txt').value=a
a=a+1
x=setTimeout("timedCount()",1000);
}
function stopCount()
{
clearTimeout(x)
}
</script>
<body>
<form>
<input type="button" value="Start count!" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
<p><font color="Green"> click on 'Start count' button to time count forever.</font></p>
<p><font color="red">click on 'Stop count' button to stop the counting.</font></p>
</body>
</html>
In this example two methods are used, one is setTimeout and another is clearTimeout. By using setTimeout method counting will start from zero. Here we have to set delaytime=1000 millisecond=1 second, so the time interval is one second. By using the clearTimeout method counting will stop.
Output: Output of the above script is as follows:
Figure 1: Output of the above script.
When you click on "Start count" the counting will start from zero as follows:
Figure 2: Counting is continuing.
When you click on "Stop count" button then counting will stop.