如何解决lodash油门功能似乎没有被调用
我第一次使用 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);
}
但是这样做...我现在得到没有控制台输出!
我做错了什么?
解决方法
_.throttle
返回新的节流函数。您的代码应该类似于:
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();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。