Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 228
Peter Ehrlich Avatar asked Mar 08 '12 04:03

Peter Ehrlich


2 Answers

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);
  };
};
like image 102
pedroteixeira Avatar answered Sep 27 '22 21:09

pedroteixeira


Ah, I didn't read the docs right! There is a function for this.

var test = _.debounce(function() { console.log('foo'); }, 3000);

Then if you call test() a few times you'll notice that only after three seconds since the last call, will the function ever be called.

This is exactly what we both were looking for... and didn't notice was right below throttle on the docs.

Underscore docs, Lo-Dash docs (what is LoDash?)

like image 33
Camilo Martin Avatar answered Sep 27 '22 19:09

Camilo Martin