Countdown minutes in Javascript

A simple way to include a countdown on any page.

This script generates a countdown which is a timestamp ("00:00:00") that "counts down" the seconds from an initial value to zero. The countdown can persist as the user leaves the page and returns later.

Persistence means that if a user leaves the page while the countdown is at, say "01:23:45", the countdown will continue from this value when the user returns to the page. If persistence is turned off the countdown will restart from the initial value (the maximum value) at each page load.

There are two versions of the script:

Demo

Note: Persistence is "on" for the example above. This means that if you leave the page, the countdown will continue upon return. Also, once the countdown reaches 00:00:00 it does not restart until you close and re-open the browser (or, delete cookies).)

Also, the demo is "version 1" (one single countdown per page)

About persistence

The persistence feature may increase the countdown duration: If a countdown is timed to 5 minutes and the user leaves the page once for 20 minutes after starting the countdown, then the countdown will not end while the user is away from the page. It will resume on next visit, and the total duration will be 25 minutes, not 5 minutes. Still, the countdown will count down for 5 minutes exactly.

This is intentional as it makes it possible to ensure that a user is exposed to some feature for a set period of time, and that this exposure can not be skipped by leaving the page temporarily. This may be useful in the context of game programming, simulations, etc.

How-to / Usage

See instructions in the script. In general it boils down to:

Use this file with a "script" tag in the page template "<head>" section:

<script type="text/javascript" src="path/to/countdown.js"></script>

Example (for version 1)
- countdown 2 mins: Include code below in the HTMl of the target page:

<script>cd_countdown(2,true);</script>

That's all.

NOTE: For version 1 the target page must have a single container element with ID "countdown_timer" inside which the countdown will be displayed. For version 2 several IDs with custom values may be set.

Source code

Click "download" link below and the code will be visible

Download

(right-click the link, and choose "Save link/target as...")

Version and License

Versions: Last update date

Version 1: 2021-08-24

Version 2: 2022-05-15

License

What? Free!