Peter Ehrlich Peter Ehrlich - 29 days ago 15
Javascript Question

underscore throttle + ensure last call

Underscore provides the method, throttle. From their docs:

Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

Now imagine the case of an autocomplete form. This means that if 'abc' is typed within a, say, 100ms window, then only a search for 'a' will be sent, and not 'bc'.

Is this a drastic oversight on the part of underscore.js? What would you suggest as a clean solution?

Answer

For this use case, you may want to use the following "buffer" function, which will apply only the last call within the wait window.

https://gist.github.com/2484196

_.buffer = function(func, wait, scope) {
  var timer = null;
  return function() {
    if(timer) clearTimeout(timer);
    var args = arguments;
    timer = setTimeout(function() {
      timer = null;
      func.apply(scope, args);
    }, wait);
  };
};
Comments