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.