JavaScript timer: setTimeout and clearTimeout

What is timer?

Timer is a device which fires an event after a preset time interval. They are usually a down counter, i.e. a counter which counts from a preset positive number towards zero. When count reaches to zero it fires an event to start. After that the counter goes into idol state and remains idol until user again sets an interval to reactivate it.

In JavaScript there is an inbuilt timer function setTimeout().

JavaScript : setTimeout

The JavaScript function window.setTimeout() takes two arguments. First one is the JavaScript expression to be executed after delay and another is the delay in millisecond. So if you run the command window.setTimeout('alert(\'delay 5 seconds\')', 5000) it will generates an alert box after 5000milisecond = 5 second.
Example:

Code | Download
<input type="button" onclick ="javascript:window.setTimeout('alert(\'delay 5 seconds\')', 5000)" value="delay 5 seconds"/>

setTimeout : Example

You can see more practical example of setTimeout() function in the article Self closing popup window with delay.

JavaScript : clearTimeout

The JavaScript function window.setTimeout() is used to reset timer set by window.setTimeout(). It takes only a single argument the id of the timeout.

clearTimeout : Example

Here we take two buttons one is to set timer to give an alert after 5 second and other is to reset that timer.

Code | Download
//between <head> and </head> tags.
<script type="text/javascript">
<!--
var id=null;
function get_alert(){id=window.setTimeout('alert(\'delay 5 seconds\')', 5000);}
function reset_alert(){
window.clearTimeout(id);
if(id!=null){alert('Reset timer');}
id=null;
-->
</script>
//between <body> and </body> tags.
<input type="button" onclick ="javascript:get_alert()" value="set" />
<input type="button" onclick ="javascript:reset_alert()" value="reset" />

Conclusion: If you reset timer without setting it no error message is generated, i.e. function clearTimeout() doesn't generate any error message for invalid timer id.

User comments:

Add comment

RAMUI WEBBLOG
HomeAboutContact SitemapTerms of useXMLForum
© 2010,  http://ramui.com   All rights reserved.
Powered by: ramui webblog® Version 1.0