【发布时间】:2021-10-27 19:01:35
【问题描述】:
我正在学习节流,但我遇到了一个问题,即我的节流方法没有等待 limit 运行时间。
const display = (msg) => {
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.
}
const throttle = (func, limit) => {
let flag = true;
return function() {
if(flag) {
func.apply(this, arguments);
flag = false;
setTimeout(() => flag = true, limit);
}
}
}
const throttleDisplay = () => {
return throttle(display("Hi"), 6000);
}
for(let i=1; i<=10; i++) {
setTimeout(throttleDisplay, i*1000);
}
我的输出是“Hi”10 次,但我不应该有 10 次 Hi,因为我在一个呼叫和另一个呼叫之间有 6 秒的等待时间。
【问题讨论】:
标签: javascript throttling