Paul Irish

Making the www great

jQuery idleTimer Plugin

There are a few cases where you want to know if the user is idle. Namely:

  • You want to preload more assets
  • You want to grab their attention to pull them back
  • You want close their banking session after 5 minutes of inactivity. (Jerk!)
  • You want the site to sneak off the screen and see if they notice ;-)

Nick Zakas wrote a script for YUI3 to handle these cases. His writeup has a great description of the architecture approach he took to the script.

In my jQuery adaptation, I did a few different things:

  1. Leveraged event namespaces for easy unbinding
  2. Considered mousewheel as activity, in addition to keyboard and mouse movement.
  3. Gave it a bit more jQuery-ish of an API

To use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// idleTimer() takes an optional argument that defines the idle timeout
// timeout is in milliseconds; defaults to 30000
$.idleTimer(10000);


$(document).bind("idle.idleTimer", function(){
 // function you want to fire when the user goes idle
});


$(document).bind("active.idleTimer", function(){
 // function you want to fire when the user becomes active again
});

// pass the string 'destroy' to stop the timer
$.idleTimer('destroy');

Get the source on github (4.6k unminified) View the demo

Note: If you want to change the timeout interval, you’ll have to destroy the existing timer first.

2009.09.22: I’ve updated the idleTimer script for a few more features…
1
2
3
4
5
// you can query if the user is idle or not with data()
$.data(document,'idleTimer');  // 'idle'  or 'active'

// you can get time elapsed since user when idle/active
$.idleTimer('getElapsedTime'); // time since state change in ms

You can get the latest code, naturally, on github.

2010.05.11: Due to popular demand, there is now support for multiple timers!!

Why would you want this? Lets say you want ..

  • One Timer to restore the forms, messages boxes, etc.
  • Another Timer of a different length timeout to notify about expiration sessions.
1
2
3
4
5
6
// bind to specific elements, allows for multiple timer instances
$(elem).idleTimer(30*1000);
$(elem).idleTimer('destroy');
$(elem).idleTimer('getElapsedTime'); // some ms something

$.data(elem,'idleTimer');  // 'idle'  or 'active'

Notice this new API is on $.fn.idleTimer, as in it works on a jQuery collection instead of just the jQuery global object.

If you’re using this along with the old $.idleTimer api, you should not do $(document).idleTimer(...)

All these element-bound timers will only watch for events inside of them. You may just want to watch page-level activity, in which case you may set up your timers on document, document.documentElement, and document.body. Those will allow three separate timers that will catch all page activity.

Again, check out the demo or view the source on github. :)

2011.03.11 : You should check out Eric Hynds’ Idle Timeout plugin. It improves a good bit on this guy here.

Comments