lodash debounce not working in anonymous function
As Palpatim explained, the reason lies in the fact that _.debounce(...)
returns a function, which when invoked does its magic.
Therefore in your #anonFunction
example, you have a key listener, which when invoked does nothing but return a function to the invoker, which does nothing with the return values from the event listener.
This is a snippet of the _.debounce(...)
definition:
_.debounce
function (func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
if (immediate && !timeout) func.apply(context, args);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
Your key event listener must invoke the returned function from _.debounce(...)
, or you can do as in your non-anonymous example and use the returned function from the _.debounce(...)
call as your event listener.
Think easier
_.debounce returns a debounced function! So instead of thinking in terms of
$el.on('keyup'), function(){
_.debounce(doYourThing,500); //uh I want to debounce this
}
you rather call the debounced function instead
var doYourThingDebounced = _.debounce(doYourThing, 500); //YES, this will always be debounced
$el.on('keyup', doYourThingDebounced);