0

Question

My context:

  • JS with ES6
  • Lodash library.
  • jQuery
  • Cordova
  • SAPUI5
  • Android

I would like to know if there is any way to limit the execution of a function to once every x milliseconds. For example, a function on a button to prevent user spamming it and make bad calls.

I saw that Lodash provides a method to execute a function only once but is not limited on time so this doesn't works for my case.

Solution Example

Thanks to backtick

var antiSpamLog = _.throttle(console.log, 2000, { 'trailing': false })
antiSpamLog("Can't spam this")
//> Can't spam this
antiSpamLog("Can't spam this")
antiSpamLog("Can't spam this")
antiSpamLog("Can't spam this")
//> Can't spam this
antiSpamLog("Can't spam this")
...
Alberto
  • 1,423
  • 18
  • 32

1 Answers1

1

Lodash provides a throttle function that does what you want.

backtick
  • 2,685
  • 10
  • 18