15.8. Displaying a Countdown Timer

NN 4, IE 4

15.8.1. Problem

You want to have a running
countdown timer showing on the page.

15.8.2. Solution

Countdown timers can take many forms. Look to the combination of HTML
and scripts in Example 15-3 of the Discussion for
inspiration for your particular timer implementation. The example
application sets the turn of the new year in the
user's time zone as the "zero
hour" for the timer, and displays a constantly
updated display of the days, hours, minutes, and seconds until that
time.

An onload event handler in the page invokes the countDown(
) function by way of the
setInterval( ) method:

<body onload="setInterval('countDown( )', 1000)">

The display is updated approximately every second because the
setInterval( ) method repeatedly invokes the
countDown( ) function until a script cancels the
timer.

15.8.3. Discussion

The display of the timer can be in a text input field (all scriptable
browsers), swappable images (IE 4 or later and NN 3 or later), or
body text (IE 4 or later and NN 6 or later). This example uses
swappable images because it lends itself to the most flexible page
designs of the choices. But for other syntactic reasons, Navigator 4
is the minimum supported browser for this example. Figure 15-2 shows the output.

Figure 2. Countdown timer with swappable image

Example 15-3 shows the complete HTML document for
this application, including the HTML and scripts.

For this example, the target date of the countdown timer is the start
of the next year in the user's local time zone. The
HTML output display is a rudimentary table with place holders for the
digit images. Because this application works with browsers that may
experience CSS formatting problems, we use the old-fashioned, but
still supported, align attribute in table cells
and name attribute in img
elements. The table is delivered to the browser with all of the
swappable images set to the zero digit representation.

The script portion of the page begins by precaching the images that
represents the numbers to prevent any delay the first time they are
needed. Ten images, each the same height and width, are loaded into
the browser's image cache while the page loads.

Several functions will execute repeatedly, and they benefit from the
one-time predefinition of constants as global variables. Because this
part of the code can run in all but first-generation browsers, it
includes a fix for a Y2K problem with the getYear(
) method of the Date
object (getFullYear( ) debuted in Version 4
browsers).

The function that executes repeatedly, countDown(
), performs the date math by comparing
the current clock setting (read approximately every second) against
the target date. Invoked by way of the window.setInterval(
) method, the countDown( ) function
executes repeatedly once every second (plus or minus system latency).

Next is the setImages(
) function, which adjusts the swappable
img element src properties.
This function must convert the numeric values passed from
countDown( ) into the URLs for the images. Calling
formatNum( ) for each countdown component returns
a string version of the number, including a leading zero where
necessary.

This application is a good demonstration of a situation where it
makes sense to use setInterval(
) to drive the repeated action. While
setTimeout( ) is intended for a single invocation
of a function after some delay, setInterval( )
automatically invokes a function repeatedly. If needed for older
browser support (pre-dating the availability of setInterval(
) in Version 4 browsers), you can simulate the behavior by
recursively invoking the countDown( ) function
from a setTimeout( ) method in the last statement
of the function:

setTimeout("countDown( )", 1000);

As with the timed autoscrolling of the page in Recipe 15.5, the
repeated calls to the countdown timer can also exhibit less than
smooth running. If you watch this code run for several seconds, you
will notice an occasional and random unevenness to the flipping of
the seconds. You can improve the smoothness by shortening the
interval delay (to 100, for example), but this means that the
function is being invoked 10 times per second, which could impact
other script processing in your page. You can experiment with
different settings to achieve the balance that feels best for your
application.

So far, we have focused on the user's local time
zone, but there may be other cases in which you want to peg the
target date and time to a unique event occurring someplace on the
planet, such as a corporate press conference announcing a new product
release. To keep the timing accurate, you need to perform some
additional calculations to get the time zone issues under control, so
that users from Australia to Greenland will see the exact same
countdown times leading up to the singular event.

The coding for this is simple, but the timekeeping may not be. To peg
the target time and date to a universal point in the future, change
the global variable declarations shown in Example 15-3 from this:

This is for the stroke of midnight on New Year's Eve
at Greenwich Mean Time (GMT). If you have
another date and time, simply plug the values into the six parameters
in the order of four-digit year, month (zero-based), date, hour,
minute, and second, but at Greenwich Mean Time. For example, if you
plan to offer a web cast of a recital at 8 P.M. in Los Angeles on
March 10, 2003, you need to determine what that time is in GMT so you
can provide a countdown timer on the announcement page. Los Angeles
is in the Pacific Time Zone, and in that part of the year, the zone
is Pacific Standard Time. The PST zone is 8 hours earlier than GMT.
When it's 8 P.M. in Los Angeles,
it's 4 A.M. the next day at GMT. Thus,
you'd set the target time for 4 A.M. on the 11th of
March (month index is 2) like this:

var targetInMS = Date.UTC(2003, 2, 11, 4, 0, 0);

There is an even easier way to figure out this GMT stuff. Set your
system clock and time zone to the local time of where the event is to
occur (you may already be there). Then run this little calculator
page to determine the GMT date and time:

If you change your system clock settings to use this calculator, be
sure to change it back to your local time and time zone.

Another kind of counter is a short-term counter for applications like
student quizzes or other controlled environments in which you need
something to time out or navigate to another page.
It's not uncommon in such cases to display, say, a
60-second counter.

The following code is a modified version of the script in Example 15-3 that displays a countdown timer for the number of
seconds passed as a parameter to the primary function: