简体   繁体   中英

Debounce function issue

I created a debounce function here is the code:

  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.

 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.

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.

Contrary, in the first example you are creating new debounced function on each "input" event

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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