I wanted to use lodash throttle to make a function callable not more than once every 4 seconds or so.
If the user tries to activate the function multiple times in succession, only the first click should start the function. However the function is called an extra time after the delay. It is called once immediately and once again after the delay.
How do I prevent the extra call?
thing = _.throttle(function() {
console.log('function runs');
}, 4000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<button onclick="thing()">click a few times</button>
(fiddle)
Like debounce, throttle is also used to limit the number of times a function is called, but, unlike debounce, throttle will call the function passed to it every time the delay ends as long as the trigger for the function is still happening.
throttle() method in lodash is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds.
Use Cases for Throttle Throttle is useful for cases where the user is carrying out a smooth or continuous event such as scrolling or resizing. In the event of animating elements based on their scroll position or handling an infinite scroll page, we can use throttle to control how often the scroll handler is called.
Throttling is used to call a function after every millisecond or a particular interval of time only the first click is executed immediately. Let's see, what will happen if throttle function is not Present in the web page. Then the number of times a button is clicked the function will be called the same number of times.
thing = _.throttle( function() {
$('#info').append('function runs' + '<br />')
}, 4000, {trailing:false});
https://lodash.com/docs/#throttle
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