Search code examples
javascriptlodash

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)


Solution

  • thing =  _.throttle( function() {
    
       $('#info').append('function runs' + '<br />') 
    
    }, 4000, {trailing:false});
    

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