简体   繁体   English

去抖 function 问题

[英]Debounce function issue

I created a debounce function here is the code:我创建了一个去抖 function 这是代码:

  function debounce(func, timeout = 300) {
        let timer;
        return (...args) => {
          if (timer) clearTimeout(timer);

          timer = setTimeout(() => {
            func.apply(this, args);
          }, timeout);
        };

Now I am using this in an onChange event for a search bar.现在我在搜索栏的 onChange 事件中使用它。

 search.addEventListener("input", (e) => {
        eventCount++;
        eventOutput.textContent = eventCount;
        debounce(() => {
          apiRequestCount++;
          apiCount.textContent = apiRequestCount;
        }, 200);
      });

but this is not working, but when I use the following code it works.但这不起作用,但是当我使用以下代码时它起作用了。

const debouncedFunction = debounce(() => {
        apiRequestCount++;
        apiCount.textContent = apiRequestCount;
      }, 200);

      search.addEventListener("input", (e) => {
        eventCount++;
        eventOutput.textContent = eventCount;
        debouncedFunction();
      });

I am not able to figure out why it is behaving like this both are almost the same, in the second one I have only stored the debounce function in a const.我无法弄清楚为什么它的行为如此两者几乎相同,在第二个中,我只将 debounce function 存储在 const 中。

You are not just stored it in a const, you also moved debounced function deplaration out of event listener and start creationg it only once.您不仅将其存储在 const 中,而且还将 debounced function deplaration 从事件侦听器中移出并仅开始创建一次。

Contrary, in the first example you are creating new debounced function on each "input" event相反,在第一个示例中,您在每个“输入”事件上创建新的去抖动 function

The debounce function returns another function, which you can think of like an object of a class (it has a "memory" of timer, which is setTimeout id), and you always invoke the same function created with debounce() function. The debounce function returns another function, which you can think of like an object of a class (it has a "memory" of timer, which is setTimeout id), and you always invoke the same function created with debounce() function. But in the first example, you create new debounced function on every input event, which creates new object unaware of previous timeouts.但在第一个示例中,您在每个输入事件上创建新的去抖动 function,这会创建新的 object,而不会意识到先前的超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM