Underline throttle + provide last call

An underscore provides a choke method. From your documents:

Creates and returns a new, throttled version of the passed function, which when called again will actually call only the original function no more than once every every millisecond of waiting. Useful for speed limit events that happen faster than you can keep up.

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

Is this decisive oversight by underscore.js? What do you offer as a clean solution?

+5
source share
4 answers

In this case, you can use the following "buffer" function, which will only apply the last call in the standby 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);
  };
};
+3
source

Ah, I didn’t read the documents directly! There is a function for this.

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

Then, if you call test()several times, you will notice that only three seconds after the last call will the function be called.

This is exactly what we both looked for ... and did not notice that it was lower throttlein the documents.

Underline documents , Documents in Lo-Dash format ( what is LoDash? )

+4
source

idle . , , - (.. ); , . , (, , ), , .

- , !

+1

, , . , . - .

0

All Articles