34,333
edits
Changes
no edit summary
In programming it is often necessary to wait a period of time before performing a task, or to set up an activity to repeat at predefined intervals. To address this need JavaScript provides what is known as ''Timeout'' support in the window Window object. This functionality essentially allows the JavaScript developer to specify in a script that a particular function, or piece of in-line JavaScript should be executed after a specified number of milliseconds have passedelapsed.
== Setting up a JavaScript Timeout ==
A JavaScript Timeout is specified using the ''setTimeout()'' method of the window Window object. The 'setTimeout()'' method takes the action to be performed (a function call or in-line script) and the time to wait in milliseconds as arguments. The method returns a timeout ID that can subsequently be used to cancel the timeout. The syntax is as follows:
id=window.setTimeout(function, delay);
In the following example an alert dialog will be displayed after 20000 milliseconds:
<pre>
</pre>
It is important to note that all other objects and elements in the window will continue to fucntion function while the timeout is counting down. A user will have no indication taht that a timeout is running in the background while visiting a web page.
== Cancelling a JavaScript Timeout ==
Once a timeout has begun there may be a requirement to cancel it before the specified time expires. This can be achieved using the ''clearTimeout()'' toegtehr together with the ID returned by the call to the ''setTimeout()'' method. The following example starts a timeout running and provides a button to enable the timeout to be cleared:
<pre>
== Setting up JavaScript Timeout to Repeat ==
You may have noticed that there is no argument to the ''setTimeout()'' method to tell javaScript JavaScript to repeat the timeout once it has expired. If, once the timeout has triggered, you need to run the timeout again all you need to do is make another call to ''setTimeout()'' within the function that was called when the timeout was triggered. We can see this in action by extendingf extending our origianl original example. The In the example below a function we have named ''timedout()'' is called after 10000 milliseconds. After the alert dialog is dismissed by the user the timeout is set up again so that the process will repeat:
<pre>