23

Calling _.debounce() causes the function to be executed multiple times instead of one time after they delay. How can I get the function within _.debounce() to be executed once after the specified delay? My use case is to perform an AJAX request after the user has stopped typing.

For example, typing into the input will cause a message to appear in the console after 1 second. In my example, you will see multiple messages appear (one for each letter you type). How would I modify my code to see only one message?

https://plnkr.co/edit/3dGm55ZFqWe4V59HLgoC

function onKeyUp() {
    _.debounce(() => {
        console.log('foo');
    }, 1000)();
}
<input onkeyup="onKeyUp()" />
Jon
  • 8,205
  • 25
  • 87
  • 146
  • Have you tried _.throttle() ? – Radioreve Mar 20 '18 at 16:14
  • 1
    @Radioreve I believe `_.throttle()` does the opposite of what I want. I am looking to perform an AJAX request after the user has finished typing. I believe `_.throttle()` would let me perform the AJAX request when the user begins typing, not when they have finished typing. – Jon Mar 20 '18 at 16:22

1 Answers1

41

You are creating a new debounced function on every keyup event. Instead you need to create it once and use this function inside (or instead) onKeyUp event handler.

var handler = _.debounce(() => {
  console.log('foo');
}, 1000)

function onKeyUp() {
  handler();
}
<script src="http://underscorejs.org/underscore-min.js"></script>
<input onkeyup="onKeyUp()" />
AlexSkorik
  • 504
  • 5
  • 8
  • 1
    Is there a reason why `handler` is a variable and not a function? Ie: `function handler() { return (_.debounce(() => { console.log('foo'); }, 1000)); }` – Jon Mar 20 '18 at 17:19
  • 2
    To clarify, is there a reason why `handler` is a function expression instead of a function declaration? How would I get the above code to work with `handler` as a function declaration? – Jon Mar 20 '18 at 17:25
  • 2
    @Jon [_.debounce()](http://underscorejs.org/#debounce) creates and returns a new debounced version of the passed function. And to be able to use this new function we need to store it somewhere. That is why it is stored as a variable. It will not work in your example with function declaration, because in this case each time, when you call `handler()` you will execute `_.debounce()` which leads to creating a new debaunced function instead of using it. – AlexSkorik Mar 20 '18 at 17:41
  • 2
    @Jon To be more precise, `handler` in my example is not a function expression. It's just a common expression like `var a = 5;` Here is [an example](https://jsfiddle.net/4sc9wL5t/14/) with some comments to clarify this. – AlexSkorik Mar 20 '18 at 18:10