Timer events (Definition)

Events that are triggered after a delay time.

Timer events are created by calling a timer set-up function and giving it a delay value. You can also cancel timeouts, but this can lead to problems because cancelling a timeout that has already been processed is prone to crashing the browser. Managing timeouts is tricky and exposes you to an area where the browser is somewhat less reliable than mainstream functionality.

Nevertheless, timer events are useful for managing refreshes and animation. You can interlock a refresh with some animation or scrolling so that the refresh exhibits as few screen redrawing artifacts as possible.

If you are really careful about memory leaks, you can build a ticker display with JavaScript. Making this clickable with an anchor is useful, but also exposes some cross-platform shortcomings and there are several ways to do this and each only works in one browser/platform combination and crashes on the others.

Because setTimeout() defines a delay from the time of execution to the time when the event is triggered, a cyclic mechanism takes no account of the processing time between setTimeout() calls. This means that the animation can become jerky. You can smooth that out by calculating how much time is left before you want the next scheduled event to occur. You need to access some kind of tick count to establish a reference time. You can do this by extracting values from a Date object and using its millisecond value. A modulo of that with the result subtracted from your ideal schedule frequency should yield a value that takes account of any processing jitter.

Automatic refreshing is sometimes called client pull.

If you want to execute something on a regular basis, then setInterval()/clearInterval() may be what you are looking for. These two methods manage an interval timer that you can set up to execute a function periodically. Because this doesn't disappear, there is less likelihood of crashing the browser if you try to clear one of these timers.


See also:Event, Event handler, Event model, Event object, Window.clearInterval(), Window.clearTimeout()


Wrox Instant JavaScript - page - 55