38

I'm attempting to debounce a button's input using the jquery debouncing library by Ben Alman. http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/

Currently this is the code that I have.

function foo() {
    console.log("It works!")
};

$(".my-btn").click(function() {
    $.debounce(250, foo);
});

The problem is that when I click the button, the function never executes. I'm not sure if I've misunderstood something but as far as I can tell, my code matches the example.

Gunther
  • 2,474
  • 4
  • 31
  • 45
  • It's a really small plugin, but why would you need it, especially for an event handler that is so easy to just unbind and rebind -> **http://jsfiddle.net/pgabaeju/** – adeneo Jan 05 '15 at 21:41
  • 2
    How do you force consumers of a jQuery plugin to install another plugin? This should be part of the core API. Also your jsfiddle example if a throttle not a debounce. – Sukima Apr 17 '15 at 20:02
  • what version of jquery is this? – Urasquirrel Sep 14 '21 at 20:27
  • 1
    @adeneo Your example of unbind/rebind executes first then ignores. Debounce ignores first then executes. There is significantly more functionality in a debounce than your example, most importantly that the most recent user input is always respected. – Ron May 03 '22 at 20:42

2 Answers2

81

I ran into the same issue. The problem is happening because the debounce function returns a new function which isn't being called anywhere.

To fix this, you will have to pass in the debouncing function as a parameter to the jquery click event. Here is the code that you should have.

$(".my-btn").click($.debounce(250, function(e) {
    console.log("It works!");
}));
Geoff
  • 826
  • 7
  • 5
10

In my case I needed to debounce a function call that was not generated directly by a jQuery event handler, and the fact that $.debounce() returns a function made it impossible to use, so I wrote a simple function called callOnce() that does the same thing as Debounce, but can be used anywhere.

You can use it by simply wrapping the function call with a call to callOnce(), e.g. callOnce(functionThatIsCalledFrequently); or callOnce(function(){ doSomething(); }

/**
 * calls the function func once within the within time window.
 * this is a debounce function which actually calls the func as
 * opposed to returning a function that would call func.
 * 
 * @param func    the function to call
 * @param within  the time window in milliseconds, defaults to 300
 * @param timerId an optional key, defaults to func
 */
function callOnce(func, within=300, timerId=null){
    window.callOnceTimers = window.callOnceTimers || {};
    if (timerId == null) 
        timerId = func;
    var timer = window.callOnceTimers[timerId];
    clearTimeout(timer);
    timer = setTimeout(() => func(), within);
    window.callOnceTimers[timerId] = timer;
}
isapir
  • 21,295
  • 13
  • 115
  • 116