Perfection Kills

by kangax

Exploring Javascript by example

← back 720 words

Detect idle state with custom events

Some time ago, Andrew Sellick posted his idle state snippet based on prototype. The idea is to capture the moment when user has been idle for certain period of time. Idle means that there was no interaction with document or viewport. You might be wondering why in the world would we need to capture user idle state. Well, I can definitely think of 2 good reasons:

  • We could pause periodical ajax requests happening on a background to prevent server overload
  • We could stop some resource intensive operations happening on a client side (i.e. animation or data processing)

Ok, so detecting idle state could be useful, but how do we go about implementing it?

Before diving into all the dirty details, I’d like to mention that Andrew’s code encaplsulates “onIdle” logic into a one single function – this is where we would have to stop our requests/calculations. Such approach is absolutely fine but to decouple things a little we could abstract them into custom events. This will allow us to subscribe anyone to independently observe idle/active state of the user and act accordingly. There are quite few very, good, explanations of custom events, just in case you’re not sure what they are, as well as prototype, based, extensions. Prototype natively supports custom events since version 1.6 (which is not yet officially released). The implementation still varies (i.e. there were some drastic changes in one of the last revisions) but overall works flawlessly. In the following example I am going to use a new way of defining events – prefixing them with pseudo namespace (which I think is more descriptive).

Ok, so let’s see what these weird things are all about.

1

First, we store events (and corresponding elements) that represent any kind of interaction in a two dimensional array. I think these should pretty much cover any user action.


var events = [
  [window, 'scroll'],
  [window, 'resize'],
  [document, 'mousemove'],
  [document, 'keydown']
];

2

Next, we are interating over this array, invoking Event.observe for each element/event pair. The observe handler is simply an anonymous function. This function will fire our custom ‘state:active’ event passing idleTime parameter. We basically encapsulate few native DOM events into one custom. To make things clear, the event is essentially just an object. It has methods such as .stop() and .findElement() as well as properties such as .target and .pageX. When firing custom event we can pass an optional object along with it – storing any additional data that might be useful later on. This data is then accessible through event.memo and in our case quite conveniently stores idle time.


events.each(function(e){
  Event.observe(e[0], e[1], function(){
    document.fire('state:active', {idleTime: new Time() - document._idleTime});
    clearTimeout(document._idleTime);
  });
});

3

Now that we have taken care of ‘state:active’ all that’s left to do is set a timer to fire the opposite event – ‘state:idle’. You can obviously change the time to anything you like. The trick here is that ‘state:idle’ event will only get fired if timer doesn’t get cleared within 5 seconds (by any of the above specified user actions)


document._timer = setTimeout(function(){
  document.fire('state:idle')
}, 5000);

4

What’s really cool is that we can now observe these custom events just like we would observe the regular ones! Note the use of memo.idleTime to retrieve data passed along with the object.


document.observe('state:idle', onStateIdle).observe('state:active', onStateActive);

onIdle = function() {
  console.log('Oh no... where is everybody?');
};
onIdleEnd = function(e) {
  console.log('Looks like user is still alive but have been idle for ', e.memo.idleTime, ' ms');
};

We can now wrap this code into a self containing class to keep things clean and unobtrusive:


var Notifier = Class.create({

  _events: [[window, 'scroll'], [window, 'resize'], [document, 'mousemove'], [document, 'keydown']],
  _timer: null,
  _idleTime: null,

  initialize: function(time) {
    this.time = time;

    this.initObservers();
    this.setTimer();
  },

  initObservers: function() {
    this._events.each(function(e) {
      Event.observe(e[0], e[1], this.onInterrupt.bind(this))
    }.bind(this))
  },

  onInterrupt: function() {
    document.fire('state:active', { idleTime: new Date() - this._idleTime });
    this.setTimer();
  },

  setTimer: function() {
    clearTimeout(this._timer);
    this._idleTime = new Date();
    this._timer = setTimeout(function() {
      document.fire('state:idle');
    }, this.time)
  }
});

Here’s a little demo page to see this in action.

Enjoy your ride.

Did you like this? Donations are welcome

comments powered by Disqus