Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create a Stopwatch in Javascript

This tutorial aims to cover different perspectives on how to create stopwatch in Javascript.

The StopWatch class in the Commons Lang library offers a handy way of timing various activities in your code. After creating a StopWatch object, you start it with a call to start(). You can pause the stopwatch with a call to suspend(), and you can start the paused stopwatch up again with a call to resume(). You can call split() to get a split time, which you can view in a readable format by calling toSplitString(). When you call split(), the stopwatch continues to run, and the regular stopwatch time can be obtained from the StopWatch object's toString() method. A call to unsplit() releases the split time so that you can call split() again. The stopwatch can be stopped with a call to stop(). If you'd like to start it again, you need to call reset(), which resets the stopwatch. At this point, you can call start() again.

Below lists the points we expect out of a stopwatch:

  • measure different intervals, even when they overlap with each other (for example one being contained in a larger one).
  • It should accept the start and stop messages.
  • It should accept the pause message: in case we are in a loop we want to sum up all the times relative to a certain operation, with a sequence of start/pause pairs.
  • It should report the total elapsed time for an operation when we send it a measure message.

Stopwatch is a simple, highly extensible, API that alows monitoring of any part of the application. It reports hits, execution times and load but can be extended to do more via custom engines. It is able to persist data in "in-memory" or real database.

Listing1: Stopwatch in Javascript code

<script language="Javascript" type="text/javascript">
window.onload = function()
{
  stopwatch('Start');
}

<!--
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
   sec++;
  if (sec == 60) {
   sec = 0;
   min = min + 1; }
  else {
   min = min; }
  if (min == 60) {
   min = 0; 
   hour += 1; }

if (sec<=9) { sec = "0" + sec; }
   document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;

  if (text == "Start") { document.clock.theButton.value = "Stop "; }
  if (text == "Stop ") { document.clock.theButton.value = "Start"; }

  if (document.clock.theButton.value == "Start") {
   window.clearTimeout(SD);
   return true; }
SD=window.setTimeout("stopwatch();", 1000);
}

function resetIt() {
  sec = -1;
  min = 0;
  hour = 0;
  if (document.clock.theButton.value == "Stop ") {
  document.clock.theButton.value = "Start"; }
  window.clearTimeout(SD);
 }
 
// -->
</script>

Also we can make use of the below javascript where we have used two functions in making of javascript stopwatch by use of two functions namely timedCount() and stopCount() as they have been described in the code below.

We can make both incrementing and decrementing stop watch in javascript using the code below by making very few changes. we can change the starting value by making changes in variable c value accordingly.

Listing2 : Here is the code for incrementing

<html>
<head>
<title>stopwatch</title>
</head>
<script type="text/javascript">
var c=0
var t
function stopCount()
{
clearTimeout(t)
}
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
if(c==61)
{
alert("time over")
stopcount()
}
t=setTimeout("timedCount()",1000)
}
</script>
<body>
<center>
<form>
 <input type="text" id="txt">
 <input type="button" value="Start stopwatch" onClick="timedCount()">
 <p>Click on the Start button above to start the stopwatch.</p>
</form>
<center>
</body>
</html>

Listing3: Here is the code for decrementing stopwatch

<html>
<head>
<title>stopwatch</title>
</head>
<script type="text/javascript">
var c=60
var t
function stopCount()
{
clearTimeout(t)
}
function timedCount()
{
document.getElementById('txt').value=c
c=c-1
if(c==-1)
{
alert("time over")
stopcount()
}
t=setTimeout("timedCount()",1000)
}
</script>
<body>
<center>
<form>
 <input type="text" id="txt">
 <input type="button" value="Start stopwatch" onClick="timedCount()">
 <p>Click on the Start button above to start the stopwatch.</p>
</form>
<center>
</body>
</html>

Asynchronous timers are the cornerstone of all time-based processes in JavaScript. From obvious things like clocks and stopwatches, to visual effects and animation, to the synchronised delays that are vital to the usability of dropdown menus.

But the problem with JavaScript timers is that they’re not very accurate. We couldn’t make a stopwatch just by incrementing x, because it wouldn’t stay in time:

Listing4: Code displaying asynchronous timer

var time = 0,
    elapsed = '0.0';
window.setInterval(function()
{
    time += 100;
    elapsed = Math.floor(time / 100) / 10;
    if(Math.round(elapsed) == elapsed) { elapsed += '.0'; }
    document.title = elapsed;
}, 100);

Web browsers, like all applications, take turns for a piece of CPU time, and the time they have to wait will vary, depending on the load. This is what causes the latency in asynchronous timers — a 200MS timer may actually take 202MS, or 204, and this will gradually send the stopwatch out of time.

Web browsers, like all applications, take turns for a piece of CPU time, and the time they have to wait will vary, depending on the load. This is what causes the latency in asynchronous timers — a 200MS timer may actually take 202MS, or 204, and this will gradually send the stopwatch out of time.

The solution in this case is not to rely on the speed of the timer at all, but rather, to query the system time freshly each loop and derive the output from that. The great thing about this approach is that it really doesn’t matter how inaccurate the timer would otherwise be, the adjustments will always keep it in time. A small amount of constant latency will be easily compensated for, but equally, a sudden large spike of latency caused by a surge of processor use (like starting an application) is just as easily moderated.

Of course even the adjusted timer can’t compensate 100% — it adjusts the speed of the next iteration, and so can’t compensate for the latency of the last iteration. But still, whatever this difference amounts to, it will be tiny compared with the cumulative effect of that discrepancy multiplied by hundreds or thousands of instances.

Output

Figure 1: Output

Conclusion

We are done with our tutorial and came up with the creation of a stop watch making use Javascript. See you next time.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login