Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading