Javascript Function Throttling

In order for throttle(func, limit) to work - there can only be one instance of its product.

The problem is that the onClick function in your example creates a new instance each time it is called.

This renders the underlying inThrottle variable meaningless, as a new copy is created for each click.

The solution is to call one single instance the product of throttle(foo, 50000) directly.

Also, foo itself should be passed (not its product).

See below for a practical example, as well as closures and scope for more info.

// Foo.
const foo = (...args) => {
  $("#respond").append("|");
}

// Throttle.
const throttle = (func, limit) => {
  let inThrottle
  return (...args) => {
    if (!inThrottle) {
      func(...args)
      inThrottle = setTimeout(() => inThrottle = false, limit)
    }
  }
}

// On Click.
const onClick = throttle(foo, 1000)

// Button - Click.
$('#button').click(onClick);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button" value="Click Me" />
<div id="respond"></div>


Your onClick is creating a new throttled function on every invoke. You have to ensure that is only throttled once

var onClick = function() {
    throttle(foo(), 50000);
};
// TO

var onClick = throttle(foo, 50000);