Timers

If you need to have animation on your page which happens over time, or if you wish to schedule a function to be called, you can use the DHTML timer functions, setInterval() and setTimeout().

Setting a Single Timeout

If you wish to set an event to happen once, you would use setTimeout(). This example will let you change the background color of a paragraph, and after one second the original color will be restored:

Change Color
This paragraph is uses the default background color (normally white) but will change to blue when the link at the left is clicked. After one second, it will revert to the original color.

HTML

The HTML for the link is:

<a href="#" onclick="return colorchange ()">Change Color</a>

The only addition is setting the onclick attribute for the link. We return the value passed by colorchange() because we want to make sure the link isn't followed when clicked (the function will always return false).

If the link should be followed, the function should return true.

The HTML source for the paragraph is:

<div id="target">
    This paragraph is uses the default
    background color (normally white) but
    will change to blue when the link at
    the left is clicked. After one second,
    it will revert to the original color.
</div>

with the only notable item being that it has an identifier so we can find the object easily.

DHTML

The function colorchange() gets called when the link is clicked:

function colorchange () {
    if (! document.getElementById)
        return false;
    var targ = document.getElementById ('target');
    if (! targ)
        return false;
    if (targ.targetid)
        clearTimeout (targ.targetid);
    targ.style.backgroundColor = '#888';
    targ.targetid = setTimeout ('resetcolor ()', 1000);
    return false;
}

The first several lines make sure that we have enough DOM support in the browser for our function to work, and that we have a target.

If we have another currently-scheduled timeout, we are sure to clear that, so the background color will persist for one second after the link is clicked.

Next we set the background color, and then set the actual timeout. The first parameter to setTimeout() is a string which gets evaluated at trigger time, and the second parameter is how many milliseconds in the future to schedule the event. The function returns a timeout ID, which we save in case we need to clear this timeout. We save the value as an instance variable in our target object, so it will be easy to find and not conflict with other objects.

One thing to point out is that this example explicitly sets the background color. You could also change the color by setting the className of the object, but IE6/Windows willnot show the style change.

The resetcolor() function gets called when the timeout is triggered:

function resetcolor () {
    var targ = document.getElementById ('target');
    if (! targ)
        return;
    targ.style.backgroundColor = '';
    targ.targetid = 0;
}

This function is pretty short since all it needs to do is clear our object-specific background color and clear the target ID we saved away.

Interval Timeouts

If you wish to have a function called at repeated intervals, you can use the setInterval() function, which acts the same as setTimer() except the timeout event is automatically armed after every trigger. This example is the same as the previous one, except the color will change every half second through different colors, returning to the default:

Change Color
This paragraph is uses the default background color (normally white) but will change through several colors when the link at the left is clicked. After going through the colors, it will revert to the original color.

The HTML for this example is just like the previous one, except it calls the colorstep() function when the link is clicked.

DHTML

The two functions used for this demonstration of interval timeouts are structured just like the timeout example. The colorstep() function contains:

function colorstep () {
    if (! document.getElementById)
        return false;
    var targ = document.getElementById ('target2');
    if (! targ)
        return false;
    if (targ.targetid)
        clearInterval (targ.targetid);
    targ.colorarray = new Array ('#ff9', '#f99', '#999', '#99f');
    targ.coloridx = 0;
    targ.style.backgroundColor = targ.colorarray[0];
    targ.targetid = setInterval ('nextcolor ()', 500);
    return false;
}

Other than calling clearInterval() instead of clearTimeout(), the first half of the function is just like colorchange() above.

We create an array which contains the background colors we wish to use, and define a variable which we use to track our position in the array. We go ahead and set the background color to the first value, set the interval, and return false to prevent the link from being followed. Every half second, nextcolor() gets called.

function nextcolor () {
    var targ = document.getElementById ('target2');
    if (! targ)
        return;
    if (++targ.coloridx < targ.colorarray.length) {
        targ.style.backgroundColor = targ.colorarray[targ.coloridx];
    } else {
        clearInterval (targ.targetid);
        targ.style.backgroundColor = '';
        targ.targetid = 0;
    }
}

After determining that we found our target object, we test if we've already stepped through our last color (++targ.coloridx increments the variable before we test it, which is what we want; we've already displayed the initial entry). If not, we set the new background color and wait for the next interval to pass. If we've displayed our last color, we clear the interval timer, reset the background color, and clear the target ID variable.