JavaScript Tip: Using Timers

Posted in JavaScript Tips
Tags: , ,

Timers are a way to add a dynamic aspect to your web pages. They can be used to create animations, open or close windows, pop up a message to the user, and even destroy a cookie for security purposes.

There are two types of timers: one that’s set once, and one that reoccurs over an interval. Both can be canceled, though the one-time timer method fires just once.

To create a nonrepeating timer, use the setTimeout method. It takes a minimum of two parameters: the function literal or function name to run the timer delay ends, and the length of the timer delay in milliseconds.

If there are any parameters to send to the function, they are listed at the end of the cal, separated by commas. The method returns the identifier of the timeout:

To clear the time out, use the clearTimeout method:

If you want the timer delay to repeat over an interval, use the setInterval. This takes two parameters, the function name and the timer interval. As with setTimeout, it return an indetifier:

Again to stop or cancel the interval timer, use the clearInterval method. If you want to have a repeating delay but still use a function literal or pass in parameters, you can use setTimeout and reset the timer when the previously set timer expires.

Leave a Reply

Your email address will not be published. Required fields are marked *

*