4umi.com/web/javascript/countdown

The countdown

Timing Javascript

Featured is a nice little script to count down a given number of seconds. Such scripts are used on forwarding pages to inform a visitor about a redirection in so many seconds, in games, and many other useful places.

The action

Enter a number of seconds for your example, check whether an alarm should ring, and press ‘Start’ to run the test.

Control
Result
Countdown complete ...

The script

The function uses the setTimeout method of the window object to call itself again after 1000 milliseconds (give or take 10 for the script to be passed down), passing the variable sec, each time decremented by one, using the fast pre-decrement operator -- on line 7. The loop is broken when it reaches 0 (zero), as per the if test on line 6.
On line 5, the letter s is attached to the second in the sweet and short syntax of the ternary operator, where the ? and the : separate the condition and statements.

var tid = null;
function countdown(sec) {
 document.getElementById( 'start' ).disabled = true;
 document.getElementById( 'tel' ).firstChild.nodeValue = 'in ' + sec + ' second' +
  ( sec===1 ? '' : 's' );
 if( sec ) {
  tid = window.setTimeout( 'countdown(' + ( --sec ) + ');', 1000 );
 } else {
  stop();
  if( document.getElementById( 'alarm' ).checked ) {
   document.body.style.backgroundColor = 'red';
   window.alert( 'Countdown has completed.' );
   document.body.style.backgroundColor = '';
  }
 }
}
function stop() {
 window.clearTimeout( tid );
 document.getElementById( 'start' ).disabled = false;
}