Monday 3 October 2011

Timeout in javascript

Timeouts are like a timer. It can allow you to execute a section of code after a specified amount of time has passed. If you have viewed this page for 30 seconds, you have probably noticed a working example of this. Here is the code used : 
<script type="text/javascript">
<!--
setTimeout("alert('Thirty seconds has passed.');",30000);
// -->
</script>

Notice that the complete ALERT area is surrounded by double quotes to signify that it belongs as a single command. Single quotes are used for the actual ALERT message so the browser won't get confused.

Any function or other command can be used in place of the ALERT example. 


Here is the layout for a Timeout : 
setTimeout ( "function or expression", delaytime );

The delaytime is entered as milliseconds. Calculate the time you want to delay in seconds. Then multiply that by 1000. For example, if you want a 3 second delay, you would enter 3000 for the delaytime. A 30 second delay would be entered as 30000.

That's good for starting a script as the visitor enters the site, but what about creating a timeout script when a button is activated? 
Top of Form
Bottom of Form
<script type="text/javascript">
<!--
function timingex( ){
setTimeout("alert('Three seconds has passed.');",3000);
}
// -->
</script>

<form>

<input type="button" VALUE="Click me!" OnClick="timingex( )">
</form>

Once the button is activated, the OnClick event goes to the function called "timingex". The function creates an ALERT box to appear after 3 seconds.