JavaScript Timeouts

From Techotopia
Revision as of 18:59, 10 May 2007 by Neil (Talk | contribs)

Jump to: navigation, search

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 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 passed.

Setting up a JavaScript Timeout

A JavaScript Timeout is specified using the setTimeout() method of the 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:



id=window.setTimeout ("alert('Timed out')", 20000);

It is important to note that all other objects and elements in the window will continue to fucntion while the timeout is counting down. A user will have no indication taht 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 with 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:


<script language="JavaScript" type="text/javascript">
newWindowObj = window.open ("", "MyWindow");
newWindowObj.blur();

id=window.setTimeout ("alert('Timed out')", 20000);


function cancelTimeout()
{
        window.clearTimeout(id); // Cancel the timeout using the id returned from setTimeout()
}

</script>

<form action="null">
  <input type="button" value="Clear Timeout" onclick="cancelTimeout()" />  
</form>