O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Displaying a Countdown Timer

NN 4, IE 4

Problem

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

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.

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.

Countdown timer with swappable image

Figure 15-2. Countdown timer with swappable image

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required