I’m learning throttling and I’m having an issue where my throttle method is not waiting the limit
time to run.
JavaScript
x
23
23
1
const display = (msg) => {
2
console.log(msg). // I know this function does not do anything, but I'm trying to understand how I can call a function inside my throttle.
3
}
4
5
const throttle = (func, limit) => {
6
let flag = true;
7
return function() {
8
if(flag) {
9
func.apply(this, arguments);
10
flag = false;
11
setTimeout(() => flag = true, limit);
12
}
13
}
14
}
15
16
const throttleDisplay = () => {
17
return throttle(display("Hi"), 6000);
18
}
19
20
for(let i=1; i<=10; i++) {
21
setTimeout(throttleDisplay, i*1000);
22
}
23
My output is “Hi” 10 times, but I shouldn’t have 10 times Hi because I have a 6s wait between one call and another.
Advertisement
Answer
throttle
takes a callback as a parameter, but you’re invoking display
immediately.
JavaScript
1
4
1
const throttleDisplay = () => {
2
return throttle(display("Hi"), 6000);
3
}
4
is exactly equivalent to
JavaScript
1
5
1
const throttleDisplay = () => {
2
const result = display("Hi");
3
return throttle(result, 6000);
4
}
5
See the problem?
You need a function that invokes display
with the argument you want instead:
JavaScript
1
4
1
const throttleDisplay = () => {
2
return throttle(() => display("Hi"), 6000);
3
}
4