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)
var alarm = {
  remind: function() {
    delete this.timeoutID;

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

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

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: Logo

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

Facebook photo

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

Connecting to %s