我throttle第一次使用 lodash 的函数来尝试限制对 API 的调用次数,但是在我的尝试中,我似乎无法让它触发调用。
我在下面包含了一个简化版本:
const _ = require('lodash');
let attempts = 0;
const incrementAttempts = () => {
console.log('incrementing attempts');
attempts++;
console.log("attempts now: " + attempts);
}
const throttledAttempts = () => {
// From my understanding, this will throttle calls to increasedAttempts to one call every 500 ms
_.throttle(incrementAttempts(), 500);
}
// We should make 5 attempts at the call
while(attempts < 5) {
throttledAttempts();
}
这最初给了我输出:
incrementing attempts
attempts now: 1
TypeError: Expected a function
at Function.throttle (/home/runner/SimilarUtterUnits/node_modules/lodash/lodash.js:10970:15)
在查找此错误后,我看到了向throttle函数添加匿名包装器的建议,所以现在我throttledAttempts看起来像:
const throttledAttempts = () => {
_.throttle(() => incrementAttempts(), 500);
}
但是这样做......我现在没有任何控制台输出!
我究竟做错了什么?