How to create a Timer with Start Stop Buttons in Javascript

Calculating time in seconds or milliseconds is sometimes necessary in javascript programming, especially if you are creating some games or animation. This page contains a simple code of javascript timer with "Start" and "Stop" buttons. If you have some basic knowledge of JS Programming then you will easily understand the logic behind it. You may utilize it to make your own timer with little bit of change in coding as per your requirement.

Running version of Script:

0 Seconds

Code:
<div> <input id="btnStart" type="button" value="Start" onclick="timestart();" /> <input id="btnStop" type="button" value="Stop" onclick="timestop();" /> <h3><span id="timer">0</span> Seconds</h3> </div> <script type="text/javascript"> var check = null; var timespent=0; var displayfrequency=100; // in milliseconds var decimalplaces=1; // seconds to be displayed in points function timestart() { var startTime = Date.now(); check = setInterval(function () { var elapsedTime = Date.now() - startTime; document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(decimalplaces); }, displayfrequency); } function timestop() { clearInterval(check); timespent=document.getElementById("timer").innerHTML; } </script>
In the above script variable displayfrequency can be adjusted to change the duration after which time displayed in changed. Similarly decimalplaces can be adjusted to change the decimal point of seconds dispalyed. Just play by changing these values and you will understand their usage.
Share this Article :
Email

No comments:

Post a Comment