Idle Ajax callback for Rails

I’m working on an application that needs an idle callback (do something after the user has been idle for N seconds). It was pretty easy to hack up once I found some example javascript code (hopefully it works in IE too…):

def on_idle(timeout, options)
  timeout *= 1000
  remote = remote_function(options)
  javascript_tag("
var alarm = {
  remind: function() {
    #{remote}
    delete this.timeoutID;
    this.setup(this.ms);
  },

  setup: function(ms) {
    this.cancel();
    var self = this;
    self.ms = ms;
    this.timeoutID = window.setTimeout(function(msg) {self.remind();}, ms);
  },

  cancel: function() {
    if(typeof this.timeoutID == "number") {
      window.clearTimeout(this.timeoutID);
      delete this.timeoutID;
    }
  }
};
alarm.setup(#{timeout});
window.onblur = function() { alarm.setup(#{timeout}) };
window.onfocus = function() { alarm.setup(#{timeout}) };
window.onmousemove = function() { alarm.setup(#{timeout}) };
")
end

I use it like so, after putting it into my application_helper.rb file.

<%= on_idle 600, :url => { :action => 'on_idle' } %>

It could probably improved by making it take some options to determine which events cause un-idleness and perhaps call a no-longer-idle hook. I’ll update this page with those changes should I get around to them.

I wonder if there’s a good, centralized place to submit these kinds of little hacks to? The Rails trac system seems to be full of spam, indicating that people aren’t triaging bugs at all.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s