const debounce = (func) => {
return (arg) => {
let timeoutId;
if (timeoutId){
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func(arg);
}, 1000);
}
}
function hello(name){
console.log("hello " + name);
}
input.addEventListener("input", debounce(hello));
在这个例子中,我应该如何去抖动并调用
hello
具有去抖动功能和名称 "Brian"
.在代码行 2
return (arg) => {
在变量中传递参数的代码是什么?我明白了
debounce(hello);
调用 debounce 函数,但我想如何传入一个变量,以便将其存储在 (arg)
中?
最佳答案
当你从一个函数返回一个函数时,你有两组参数:那些给外部函数的和那些给内部函数的,所以模式本质上是
debounce(someFunction)("argument 1 to someFunction", "argument 2 to someFunction");
您可以将其分布在几行上。请注意,您的去抖功能不正确。它会延迟,但不会批量更新,因为
timeoutId
是返回函数的局部,违背了闭包的目的。此外,使用
...args
而不是 args
并将超时设置为参数而不是在函数中对其进行硬编码使去抖动更加可重复使用。这是所有这些的一个最小示例:
const debounce = (func, timeout=1000) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func(...args);
}, timeout);
};
};
const hello = name => console.log("hello " + name);
const debouncedHello = debounce(hello);
document.querySelector("input")
.addEventListener("input", e => debouncedHello(e.target.value));
<input value="test">
关于javascript - 如何在去抖动中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61334955/