如何在防抖函数中传入参数

6
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); 调用了防抖函数,但是我应该如何传递一个变量,以便它被存储在 (arg) 中?

2个回答

9
当你从一个函数返回另一个函数时,你有两组参数:外部函数的参数和内部函数的参数,所以这个模式基本上是:
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">


2

VanillaJS 解决方案。

function debounce(func, timeout = 300) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, timeout);
  };
}

const updateQuantityDebounce = debounce((a,b) => updateNewValue(a,b));

function updateNewValue(id, quantity) {
  console.log({ id, quantity }); // do network requests here.
}

要使用它,假设从内部的click事件监听器中

   function fn() {
        updateQuantityDebounce(id, newValue)
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接