Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore Debounce Calling Multiple Times

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()" />
like image 699
Jon Avatar asked Mar 20 '18 16:03

Jon


People also ask

What is the difference between debounce time and throttle time?

# Throttling tells us the maximum number of times a function can be called over a period of time. It executes the function once every 100 milliseconds. # Debouncing means that a function will not be called again until a certain amount of time has passed without it being called.

Does debounce use setTimeout?

Each time the debounced function is invoked, clear the current pending timeout with clearTimeout() . Use setTimeout() to create a new timeout that delays invoking the function until at least ms milliseconds have elapsed.

What is leading and trailing in debounce?

Debounce with {leading: true} is passing first received value to debounced function. And then it works in same way as default debounce. Debounce with {leading: true, trailing: false} will result in these values being processed. So, as you see, using different settings you can get different results.


1 Answers

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()" />
like image 158
AlexSkorik Avatar answered Oct 04 '22 22:10

AlexSkorik