【问题标题】:My throttle function is not waiting the limit time我的油门功能没有等待限制时间
【发布时间】: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


    【解决方案1】:

    throttlecallback 作为参数,但您会立即调用 display

    const throttleDisplay = () => {
        return throttle(display("Hi"), 6000);
    }
    

    完全等价于

    const throttleDisplay = () => {
        const result = display("Hi");
        return throttle(result, 6000);
    }
    

    看到问题了吗?

    您需要一个使用您想要的参数调用display 的函数:

    const throttleDisplay = () => {
        return throttle(() => display("Hi"), 6000);
    }
    

    【讨论】:

    • 谢谢,我明白了你所说的,但是在将throttleDisplay 更改为返回return throttle(() =&gt; display("Hi"), 6000); 后,我的console.log 中没有显示任何内容
    • 我想通了。应该是const throttleDisplay = throttle(() =&gt; display("Hi"), 6000);
    猜你喜欢
    • 2021-07-15
    • 2012-09-02
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    相关资源
    最近更新 更多