Paul McFedries' Web Home


JavaScript Programs

Setting Up a JavaScript Timer

This page shows you how to set up a timer using JavaScript. Here's an example:


Click the button below and then keep your eye on the status bar:


Here's the script:
<SCRIPT LANGUAGE = "JavaScript">
<!--
var secs
var timerID = null
var timerRunning = false
var delay = 1000

function InitializeTimer()
{
    // Set the length of the timer, in seconds
    secs = 10
    StopTheClock()
    StartTheTimer()
}

function StopTheClock()
{
    if(timerRunning)
        clearTimeout(timerID)
    timerRunning = false
}

function StartTheTimer()
{
    if (secs==0)
    {
        StopTheClock()
        // Here's where you put something useful that's
        // supposed to happen after the allotted time.
        // For example, you could display a message:
        alert("You have just wasted 10 seconds of your life.")
    }
    else
    {
        self.status = secs
        secs = secs - 1
        timerRunning = true
        timerID = self.setTimeout("StartTheTimer()", delay)
    }
}
//-->
</SCRIPT>
To use this script, copy everything between and including the <SCRIPT> and </SCRIPT> tags and insert it on your page between the </HEAD> and <BODY> tags.

The following line sets the length, in seconds, of the timer:

secs = 10

The code decreases the "secs" variable by 1 each second. When "secs" gets to 0, the clock is stopped and that's when you do whatever it is you want to do once the timer is done (such as display a message or send the user to another page).

In the example above, I use a simple form button to start the timer (it also displays the countdown in the status bar). You could also start the timer (that is, run the InitializeTimer() function) automatically by adding the following to the <BODY> tag:

onLoad="InitializeTimer()"


Copyright © 1995 - 2014 Paul McFedries and Logophilia Limited