JS - 将函数执行限制为每秒一次

JS - Limit function execution to once a second

问题

我的背景:

我想知道是否有任何方法可以将函数的执行限制为每 x 毫秒执行一次。例如,按钮上的功能可防止用户向其发送垃圾邮件和进行错误调用。

我看到 Lodash provides a method 只执行一次函数但没有时间限制,所以这不适用于我的情况。

解决方案示例

感谢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")
...

Lodash 提供了一个 throttle function 可以满足您的需求。