Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash throttle - prevent function from being called an extra time after delay

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 image 742
Galivan Avatar asked Dec 20 '18 14:12

Galivan


People also ask

Should I use throttle or debounce?

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.

What does Lodash throttle do?

throttle() method in lodash is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds.

When to use throttling?

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.

What is event throttling?

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.


1 Answers

thing =  _.throttle( function() {

   $('#info').append('function runs' + '<br />') 

}, 4000, {trailing:false});

https://lodash.com/docs/#throttle

like image 179
enno.void Avatar answered Oct 21 '22 03:10

enno.void