Reputation: 6326
I'm using lodash's throttle
function for the first time to try and throttle the number of calls to an API, however in my attempts I can't seem to get it to trigger a call.
I have included a simplified version below:
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();
}
This initially gave me the output:
incrementing attempts
attempts now: 1
TypeError: Expected a function
at Function.throttle (/home/runner/SimilarUtterUnits/node_modules/lodash/lodash.js:10970:15)
After looking up this error I saw a suggestion to add an anonymous wrapper to the throttle
function, so now my throttledAttempts
looks like:
const throttledAttempts = () => {
_.throttle(() => incrementAttempts(), 500);
}
However doing this... I now get NO console output whatsoever!
What am I doing wrong?
Upvotes: 0
Views: 1850
Reputation: 414
The _.throttle
returns the new throttled function. Your code should be something like:
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();
}
Upvotes: 3