Underscore Debounce Calling Multiple Times

Jon picture Jon · Mar 20, 2018 · Viewed 7.7k times · Source

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()" />

Answer

AlexSkorik picture AlexSkorik · Mar 20, 2018

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()" />