I'm trying to debounce a function using Lodash, and while it's invoking the function, it doesn't seem to debounce it at all. My issue doesn't seem to be the same mistake as what I've seen elsewhere on SO or Google (generally, that they're not invoking the function that _.debounce
returns).
My currently super-simple implementation is as follows (in Angular with CoffeeScript):
s.search = -> _.debounce( s._makeSearchRequest, 1000 )()
s._makeSearchRequest = -> console.log("making search request")
In JS, I believe that's:
s.search = function() { _.debounce( s._makeSearchRequest, 1000 )() }
s._makeSearchRequest = function() { console.log("making search request") }
I run s.search()
by typing into an input box, and if I type gibberish very quickly, the console prints out "making search request" on every key press, so many times per second -- indicating that it hasn't been debounced at all.
Any ideas what's I'm doing wrong?
_.debounce
creates a function that debounces the function that's passed into it. What yours.search
function is doing is calling_.debounce
all over again every times.search
is called. This creates a whole new function every time, so there's nothing to debounce.So the solution is to remove the arrow and the extra pair of parentheses, and make sure that
s._makeSearchRequest
is defined before you access it:Example (using JavaScript):
Try this:
POC: http://jsfiddle.net/bvaughn/3saj6znk/