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()" />
# 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.
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.
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.
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()" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With