Working with Timers in JavaScript

Often you’ll run into a situation where you need to trigger an event dynamically in a web page, without the website visitor doing anything. JavaScript provides two simple functions that allow you to schedule an event to trigger at a preselected time.

The setTimeout() function allows you to schedule a specified function to trigger at a specific time from the current time:

setTimeout(function, time);

The function parameter specifies the name of the function to trigger, while the time parameter specifies the amount of time (in milliseconds) for the browser to wait until triggering the function. An example would be the following, which triggers the myfunction() function after waiting five seconds:

setTimeout(myfunction, 5000);

You may also run into situations where you need a specific function to trigger repeatedly at a specific time interval, such as if your application needs to refresh data from the application database on the server. Instead of having to set multiple setTimeout() functions, you can use the setInterval() function:

setInterval(function, time);

With the setInterval() function, JavaScript repeats the event trigger for the specified number of milliseconds, and repeats the function for each interval.

If you need to disable the timer functions before they trigger, you use the clearTimeout() and clearInterval() functions. You’ll need to include the value returned by the individual functions when they’re set as the parameter:

$timer = setInterval(myfunction, 5000);

clearInterval($timer);

With the use of the timer functions in PHP, you can trigger automatic updates to a web page at a regular interval, checking for updated data. This comes in handy when working with Ajax applications.

For Dummies: The Podcast

Check out the brand new podcast series that makes learning easy with host Eric Martsolf.