Timing Events: Clocks and Counters

 

Timing Events.  In order to develop certain sorts of dynamics on the web one needs to be able to control timing.  Some examples of these sorts of things include using clocks to determine when an event should occur, setting off an alarm, timing a slide show.

We will make use of two major built-in functions in order to do a lot of our timing.  The command

setTimeout(code, delay)

is the main way that a developer can tell JavaScript to execute some code at some point in the future after a particular delay.  What is within the setTimeout is executed after the pre-specified delay measured  in milliseconds.

The main way a developer can tell the program to terminate what it is doing is with a 

clearTimeout(timeoutID)

command.  This command will terminate code that has been initiated or invoked using the setTimeout function as identified by the timeoutID.

In general, you do not want to set the timing in programs so that it depend on the cycle time in a computer because different computers execute at different speeds.  It is important to have a more objective measure such as milliseconds.

A Second Counter.  The first program we will develop is a simple second counter that displays the number of seconds since a command button has been pushed.  It also includes a button to stop this counting.  The following code should be copied into a file called StopAndStart.html.

 

<html>
<head>
<title>Stop and Start</title>
<script language="JavaScript">

var the_timeout;

function upDate()
{
var the_number = window.document.the_form.the_text.value;
the_number = parseInt(the_number) + 1;
window.document.the_form.the_text.value = the_number;
the_timeout = setTimeout("upDate();", 1000);
}

</script>
</head>

<body bgcolor="000055" text="cccccc">

<form name="the_form">
<input type="text" name="the_text" value=0><br>
<input type="button" value="Start Timer" onClick="upDate();">
<input type="button" value="Stop Timer" onClick="clearTimeout(the_timeout);">

</form>

</body>
</html>

 

When this is uploaded you should get something like the following.

 

 

Notice that the code has a parseInt( ) function associated because IE tends to convert everything it can to strings.  The other important thing to notice is how the upDate( ) function is called from within the upDate function using a setTimeout( ) function to time its execution.  The 1000 causes the display in the textbox once every second.  The results of the setTimeout( ) function are assigned to the_timeout, which is what is terminated in the clearTimeout( ) function.  

Stop and Start Clean.  Unfortunately, sometimes if the user hits the start button multiple times it can actually speed up the execution of the program so that the timing is incorrect since it has multiple timing processes running simultaneously.  You may want to try this with the previous program to see what happens.

In order to eliminate this glitch if the user decides to play with your program you need to stop the program and start it each time you start it.  The following code does the trick and should be called StopAndStartClean.html.

 

<html>
<head>
<title>Stop and Start</title>
<script language="JavaScript">

var the_timeout;

function upDate()
{
var the_number = window.document.the_form.the_text.value;
the_number = parseInt(the_number) + 1;
window.document.the_form.the_text.value = the_number;
the_timeout = setTimeout("upDate();", 1000);
}

</script>
</head>

<body bgcolor="000055" text="cccccc">

<form name="the_form">
<input type="text" name="the_text" value=0><br>
<input type="button" value="Start Timer" onClick="clearTimeout(the_timeout); upDate();">
<input type="button" value="Stop Timer" onClick="clearTimeout(the_timeout);">

</form>

</body>
</html>

 

The only change in the code is in the line

<input type="button" value="Start Timer" onClick="clearTimeout(the_timeout); upDate();">

which has been highlighted.

Developing a Clock.  Now we are going to upgrade our example to give us more developed information, a more involved current time being updated once each second.  This will be executed somewhat differently since we will re-invoke the Date( ) function once each second.  Thus we don't need to increment our own counter.

The following set of code you should save as StopAndStartClock.html.

 

<html>
<head>
<title>Stop and Start</title>
<script language="JavaScript">

var the_timeout;

function writeTime()
{
// get a date object
var today = new Date();
// parse some information from the object
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();

// clean up the minutes and seconds in case they are in single digits
minutes = fixTime(minutes);
seconds = fixTime(seconds);

// put together the string and write it out
var the_time=hours + ":" + minutes + ":" + seconds;
window.document.the_form.the_text.value = the_time;

// run this function in a second
the_timeout = setTimeout('writeTime();', 1000);
}

function fixTime(the_time)
{
if (the_time < 10)
{
the_time = "0" + the_time;
}
return the_time;
}

</script>
</head>

<body bgcolor="000055" text="cccccc">

<form name="the_form">
<input type="text" name="the_text"><br>
<input type="button" value="Start the Clock" onClick="writeTime();">
<input type="button" value="Stop the Clock" onClick="clearTimeout(the_timeout);">

</form>

</body>
</html>

 

One of the more important functions is the fixTime( ) which takes a single digit seconds or minutes figure and pre-appends a "0" so that it will display properly.

This code essentially executes the writeTime( ) function every thousand milliseconds, or once each second.  The termination of the clock update process is done with the clearTimeout( ) function, the same as we just did with the second counter.

Remember, because we are redisplaying and recalling the Date( ) function once each second, and parsing it to get our inputs, we didn't need to deal with incrementing seconds and then adjusting the rest of the display as the seconds grow to minutes grow to hours.

What should appear in your browser when this file is uploaded and executed is something similar to the following.