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?
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);
};
};
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?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With