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:

  idle: function(code, delay) {
    var handle;
    return function() {
      if (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() {
  }, 2000);

  }, 1000);


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..

Let’s keep in touch

Reach out on Twitter or subscribe for (very) occasional updates.

Hey, I'm RJ: sometimes-writer and intermittent micropoet. Broadcasts live from the Rose City.