-1

I built one JavaScript debounce function, I need JavaScript expert's opinion if this is the correct way to do it and if not then what is the flaw in this current function. Thanks in advance for your opinion this will help me to learn.

var debounce = function(inpFun, wait) {
    var timeout;
    return function () {
        if(!timeout) {
            inpFun.apply(this, arguments);
            timeout = setTimeout(function() {
                timeout = undefined;
            }, wait);
        }
        else {
            console.log("Debouncing");
        }
    }
};

var buttonClickFunction = debounce(function (event) {
    console.log("Button Clicked");
    console.log(event.target.id);
}, 2000);



document.querySelector("#button1").addEventListener("click", buttonClickFunction);
<button id="button1">Button</button>
Keith
  • 22,005
  • 2
  • 27
  • 44

1 Answers1

1

In my opinion the most useful thing to do in situations like these is to look at what the pros did. So lodash and underscore both provide implementations of debounce, and you can find them like this:

  1. docs: https://lodash.com/docs/4.17.10#debounce
  2. code: https://github.com/lodash/lodash/blob/master/debounce.js

If you want to understand this kind of code deeply, read the commit history for that file, read the blogpost about the difference between throttle and debounce in the first link, and in general just absorb as much as you can from what others struggled with.

Milimetric
  • 13,411
  • 4
  • 44
  • 56