Mootools Idle Spy - Detecting the idle status

Our mission as programmers is to take care of our users and our server resources. Ajax applications tend to make constant requests to the server, and even if you change to another window or tab often the apps continue to run wasting CPU, bandwidth and other server resources.

Imagine an application like Gmail, that is constantly checking if there are new mails on the server for display, plus updating every minute the dates in time ago format to show the elapsed time since the receipt of mail. If we change to other tab, many of these actions should stop until you get back. If like me you use to open dozens of tabs at once and in a browser such as Firefox(memory greedy), be sure that the apps that do not optimize their resources will eventually saturate the browser.

Today I bring IdleSpy a Mootools class that monitors mouse and keyboard events to determine whether the user is interacting with the page and establish a state of idle to stop certain actions or send a message and alert the user.

?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
27
28
29
30
31
32
33
34
35
36
37
38
39
  var IdleSpy = new Class({
    Implements: [Options, Events],
 
    options: {
      idleTime: 60000 //1 min
    },
 
    initialize: function(options) {
      this.setOptions(options);
      this.idle = false;
 
      document.id(document.body).addEvents({
        'mousemove': this.doBack.bind(this),
        'mousewheel': this.doBack.bind(this),
        'keydown': this.doBack.bind(this)
      });
    },
 
    start: function() {
      this.idleTimer = this.doIdle.delay(this.options.idleTime, this);
    },
 
    doBack: function() {
      if (this.idleTimer) {
        $clear(this.idleTimer);
      }
      if (this.idle) {
        this.idle = false;
        this.fireEvent('back');
      }
      this.start();
    },
 
    doIdle: function() {
      this.idle = true;
      this.fireEvent('idle');
      this.idleTimer = this.doIdle.delay(this.options.idleTime, this);
    }
  });

The class is simple to use, create an instance by passing as parameter the time in milliseconds to consider the state of idle and we can hear the events back and idle or be notified when the user returns to interact with the page.

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
 var idleSpy = new IdleSpy({
   idleTime: 300000
 });
 
 idleSpy.addEvents({
   'idle': function() { /* on user idle code here */ },
   'back': function() { /* on user back code here */ }
 });
 
 idleSpy.start();

For other AJAX frameworks:

I haven’t tested it enough yet, so I wait for your comments ;)

Update 1: Added mousewheel event to the spy
Update 2: Fixed bug pointed by eneko, added this.start() to the onBack
If you want to check what I am working on now, then follow me at twitter @aartiles24

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Bitacoras.com
  • E-mail this story to a friend!
  • Meneame
  • MySpace
  • Netvibes
  • Reddit
  • StumbleUpon
  • Technorati
  • Wikio
Comentarios

Información Bitacoras.com…

Valora en Bitacoras.com: Nuestra misión como programadores es velar por los recursos de nuestros usuarios y por los de nuestro servidor. Las aplicaciones ajax suelen realizar constantes pedidos al servidor, y aunque cambiemos de ventana o pestaña sue…

[...] This post was mentioned on Twitter by Alfredo Artiles, Noticias sobre AJAX. Noticias sobre AJAX said: RT @aartiles24: Idle Spy para #Mootools - Detectando la ausencia de interacción http://bit.ly/8ofv06 #ajax [...]

I love this! You may want to consider a mousewheel event also.

Really nice one.
May be the analytics vendors should inspire from this to have the real elapsed time on the site (last page not counted)

Great idea, although if I’m not mistaken there is a minor bug. Once the doBack function is called, the timer gets cleared and never set again.

You should call this.start() just after clearing the timer on doBack().

By the way, I love your default avatar, hahaha. Very appropriate for my previous comment :P

@david: Thanks, added!

@memoclic: Good idea, them should do something like this

@eneko: I had that fixed on my real app, i forgot to fix it here too, thanks for notifying me.

[...] Artiles nos vuelve a deleitar con un espectacular script con el que aprovecharemos al máximo los recursos del usuarios y los de nuestro servidor haciendo [...]

Muy interesante tendre que empezar a trabajar tambien con mootols , pero es que mi amigo jquery me tira mucho…

Pero este plugin esta genial… a ver si me animo y con el permiso del creador lo migro a jquery.

[...] ha publicado un post en el que habla de la entrada que Alfredo Artiles ha escrito en el que nos muestra un script con el que podremos controlar el uso de Ajax dependiendo [...]

Deja un comentario

(requerido)

(requerido)