Skip to Content

Idling functions

One of the (very few) functions missing from the singularly useful Underscore.js toolkit is _.idle, a helper that defers a function’s execution until the function has not been called for a certain period of time. Bootstrapped into underscore with _.mixin, it looks like this:

_.mixin({
  idle: function(code, delay) {
    var handle;
    return function() {
      if (handle) { 
        window.clearTimeout(handle); 
      }
      handle = window.setTimeout(_.bind(code, this), delay);
    }
  }
});

All that idle is doing is creating a function that will run code after delay milliseconds have elapsed. Any time the function is called, the timer referenced by handle will reset (and continue resetting) until the function has not been called for the specified period of time. Not too complicated, but an incredibly useful tool for building more “natural” user interfaces.

Consider the useless but illustrative example of using idle to keep a function from toc-ing before the application has had time to tic:

var foobar = _.idle(function() {
    alert('toc');
  }, 2000);

window.setTimeout(function(){
    alert('tic');
    foobar();
  }, 1000);

foobar();

Pointless, but the same behavior can apply to useful tasks, too. Like waiting to perform form validation until after user input is finished. Or throttling polling frequency when a realtime application is standing idle. If lazy’s the order of the day, it might just have a new best friend..