Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: Intermediate
Jan 6, 2000

Using the SetTimeout() Function

Browsers Targeted: Internet Explorer 3+, Netscape 3 and 4

Sometimes, you need to set up events to happen at periodic intervals. Perhaps the simplest application of this is a clock. While both JavaScript and VBScript have time functions (through the Date object), a clock requires that you update this time regularly. As there is no periodic event that you can automatically query thrown by the document, one way of updating such a clock would be to use the SetTimeout() function. Taking the three arguments of an expression to call (as a string), the number of milliseconds to wait and an optional language specifier for interpreting the expression (the default value for this is "JavaScript"), the setTimeout function returns a numeric id that identifies the timeout. Then, after the requested interval, the expression is called in the specified language.

< p>You can kill a timeout by passing the ID of the timeout to the function clearTimeout(). This is especially useful for making sure that the system doesn't attempt to call a setTimeout function on a different page after you've left the original page.

0:00:00
 
<script language="JavaScript">
var clockTimeoutID;
function updateClock(id){
    var me=document.all(id);
	var dt=new Date();
	hr=dt.getHours();
	if (hr==12){
		hrs="12"
		meridian=" PM"
		}
	else {
		if (Math.floor((hr-12)/Math.abs(hr-12)) ==-1){
			hrs=""+hr
			meridian=" AM"
			}
		else {
			if (hr==0){
				hrs="12"
				meridian=" AM"
				}
			else {
				hrs=""+(hr-12)
				meridian=" PM"
				}
			}
		}
	me.innerHTML=hrs+":"+dt.getMinutes()+":"+dt.getSeconds()+meridian;
	clockTimeoutID=setTimeout("updateClock('"+id+"')",1000,"JavaScript")
	}
	
function killClock(){
	clearTimeout(clockTimeoutID);
	}
	
window.onunload=killClock;
</script>
 
<div id="clock" style="font-weight:bold;font-size:24pt;color:blue;">0:00:00</div>

 
<script>
updateClock('clock');
</script>
Kurt Cagle
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap