PHP, MySQL, & JavaScript All-in-One For Dummies
Book image
Explore Book Buy On Amazon
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(<em>function</em>, <em>time</em>);

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.

About This Article

This article is from the book:

About the book author:

Richard Blum has more than 30 years of experience as a systems administrator and programmer. He teaches online courses in PHP, JavaScript, HTML5, and CSS3 programming, and authored the latest edition of Linux For Dummies.

This article can be found in the category: