W3hobbyist

Snippets and resources for PHP, MySQL, JavaScript-AJAX

Archive for the ‘javascript’ tag

Auto-logout after some time of inactivity with JavaScript

without comments

Logging out a user after a particular period of inactivity is a good measure(!?) to ensure that the user is there attending the screen and has not left it unattended. I have commonly seen such implementation while reading my webmails. If there is no activity for 5 minutes, I am auto-logged out because the system assumes that I may not be sitting in front of the PC and hence somebody else may get an opportunity to read my emails.

Logic:

You can achieve the same inactivity-induced auto-logout by using javascript. The logic is:

  1. Start an timer as soon as the page loads.
  2. On every activity, reset the timer. Since there is no in-built javascript function to reset the timer, to reset the timer, we have to first clear the previous timer and then immediately implement another timer.
  3. If the timer runs out due to inactivity, redirect the user to your logout page

The JavaScript:

[-]View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script type="text/javascript">
function set_interval()
{
//the interval 'timer' is set as soon as the page loads
timer=setInterval("auto_logout()",10000);
// the figure '10000' above indicates how many milliseconds the timer be set to.
//Eg: to set it to 5 mins, calculate 5min= 5x60=300 sec = 300,000 millisec. So set it to 3000000
}
 
function reset_interval()
{
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove   2. mouseclick   3. key press 4. scroliing
//first step: clear the existing timer
clearInterval(timer);
//second step: implement the timer again
timer=setInterval("auto_logout()",10000);
..completed the reset of the timer
}
 
function auto_logout()
{
//this function will redirect the user to the logout script
window.location="your_logout_script_location_here";
}
</script>

The HTML tags

The body tag should listen to these 3 events to record activity.

  1. Mouse move
  2. Mouse click
  3. Key press
  4. Scrolling

The markup would thus be

1
2
3
4
.
<body onmousemove="reset_interval()" onclick="reset_interval()" onkeypress="reset_interval()" onscroll="reset_interval()">
.
.

Thats it. Your inactivity-induced auto-logout is ready to be implemented!

Written by Rohan Shenoy

June 12th, 2008 at 12:01 am