gpt4 book ai didi

javascript - 实现去抖: how to make three invocations result in one effective call?

转载 作者:行者123 更新时间:2023-12-02 22:06:32 24 4
gpt4 key购买 nike

如何使用 setTimeOut 调用一个函数三次,但只在 100 毫秒后打印一次?

这是我必须实现的 debounce 的定义:

Debounce ignores the calls made to it during the timer is running and when the timer expires it calls the function with the last function call arguments, so I want to achieve that with Javascript

函数将按如下方式去抖:

receivedEvent = debounce(receivedEvent, 100)

我的尝试:

function debounce(func, timeInterval) {
return (args) => {
setTimeout(func, timeInterval)

}
}

function receivedEvent() {
console.log('receive')
}

receivedEvent();
receivedEvent();
receivedEvent();

但这仍然会产生 3 个输出。我需要它根据要求只产生一个输出。

最佳答案

在您的尝试中,您没有调用debounce,而只是调用了您自己的函数receivedEvent。也许测试您的尝试的网站会为您执行此操作,但我们无法从您的问题中得知这一点。只要确保它被调用即可。

要测试需求,您需要使用更好的用例:一个基于接收参数的函数的用例。这是必需的,因为您必须使用最后传递的参数证明超时后调用去抖函数。

此模式的关键是在闭包中使用变量:

function debounce(func, timeInterval) {
let timer;
let lastArgs;
return (...args) => {
lastArgs = args; // update so we remember last used args
if (timer) return; // not ready yet to call function...
timer = setTimeout(() => {
func(...lastArgs);
timer = 0; // reset timer (to allow more calls...)
}, timeInterval);
}
}

function receivedEvent(arg) {
console.log('receive ' + arg)
}

receivedEvent = debounce(receivedEvent, 100)

receivedEvent("a");
receivedEvent("b");
receivedEvent("c");

// Output will be "c" after 100ms

请注意,问题对“debounce”的定义与通常的定义略有不同,其中第一次调用实际上立即调用该函数,然后才开始超时(冷却周期)。

关于javascript - 实现去抖: how to make three invocations result in one effective call?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59697033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com