Tuesday, November 17, 2009

Javascript Timeout Clock

It can be pretty annoying for a user when an application times out. Below is a javascript clock that will inform the user that they have timed out. You can set the timeOut value to a number. The maximum is 60 minutes. The clock will display after 5 minutes and when the user times out, it will change to red.

Timeout clock
Paste this into your head tag on your html page


<script language="JavaScript" type="text/JavaScript">
//Written by Greg Dias
//Assuming the timeout is 60 minutes, will display red if the system has timed out.
//This timer will only display when the user is 5 minutes before timing out.
var timerID = 0;
var tStart = null;
var overHour=0;
var tempvalue="";
var timeOut=6; //SET LENGTH OF TIMEOUT HERE IN MINUTES maximum 60 minutes
function UpdateTimer() {
if(timerID) {
clearTimeout(timerID);
clockID = 0;
}
if(!tStart)
{tStart = new Date();}
var tDate = new Date();
var tDiff = tDate.getTime() - tStart.getTime();
tDate.setTime(tDiff);
if(overHour>0)
{
document.forms[0].theTime.value = "You have timed out!"
document.forms[0].theTime.style.backgroundColor="red"
}
else
{
tempvalue= "You will time out in: "
+ ((timeOut-1)-tDate.getMinutes()) + ":"
+ (60-tDate.getSeconds());
if(((timeOut-1)-tDate.getMinutes())>4)
{
document.forms[0].theTime.value="";
}
else
{
document.forms[0].theTime.value=tempvalue;
}
if((((timeOut-1)-tDate.getMinutes())<=0)&&((60-tDate.getSeconds())<=2))
{
overHour=1;
}
}
timerID = setTimeout("UpdateTimer()", 1000);
}
function Start() {
tStart = new Date();
document.forms[0].theTime.value = "";
timerID = setTimeout("UpdateTimer()", 1000);
}
function Stop() {
if(timerID) {
clearTimeout(timerID);
timerID = 0;
}
tStart = null;
}
function Reset() {
tStart = null;
document.forms[0].theTime.value = "";
}

</script>

Place this code where you want the clock to display.

<input type=text style="" readonly name="theTime" size=24>

Put this in your body tag to start the clock when the page is loaded.

onload="javascript:Start()"


0 comments: