lodash 油门功能似乎没有被调用

lodash throttle function doesn't seem to be called

我第一次使用 lodash 的 throttle 函数来尝试限制对 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); 
}

但是这样做...我现在得到 NO 控制台输出!

我做错了什么?

_.throttle returns 新的节流功能。你的代码应该是这样的:

let attempts = 0;

const incrementAttempts = () => {
  console.log('incrementing attempts');
  attempts++;
  console.log("attempts now: " + attempts);
}

const throttledAttempts = _.throttle(incrementAttempts, 500);

// We should make 5 attempts at the call
while(attempts < 5) {
  throttledAttempts();
}