如何在 debounce 中传入参数

Bri*_*Bui 7 javascript closures arguments debouncing

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));
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我该如何去抖并hello使用 debounce 和 name 调用该函数"Brian"

在代码行 2 上,return (arg) => {在变量中传递参数的代码是什么?

我知道它debounce(hello);调用了 debounce 函数,但是我该如何传递一个变量以便将其存储在中(arg)

ggo*_*len 10

当您从函数返回函数时,您有两组参数:外部函数的参数和内部函数的参数,因此该模式本质上是

debounce(someFunction)("argument 1 to someFunction", "argument 2 to someFunction");
Run Code Online (Sandbox Code Playgroud)

您可以将其分散在几行中。该模式称为柯里化

请注意,您的去抖动器功能不正确。它会延迟,但不会批量更新,因为它timeoutId对于返回的函数来说是本地的,从而违背了闭包的目的。

此外,使用...args而不是args使超时成为一个参数,而不是在函数中将其硬编码,使得去抖更加可恢复。

这是所有这一切的一个最小示例:

debounce(someFunction)("argument 1 to someFunction", "argument 2 to someFunction");
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)