Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debounce function in jQuery

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.

like image 612
Gunther Avatar asked Jan 05 '15 20:01

Gunther


People also ask

Does jQuery have debounce function?

Using jQuery throttle / debounce, you can pass a delay and function to $. debounce to get a new function, that when called repetitively, executes the original function just once per "bunch" of calls. This can be especially useful for rate limiting execution of handlers on events that will trigger AJAX requests.

What is debounce function?

The debounce() function forces a function to wait a certain amount of time before running again. The function is built to limit the number of times a function is called. The Send Request() function is debounced. Requests are sent only after fixed time intervals regardless of how many times the user presses the button.

What is Debouncing in JavaScript?

Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, that it stalls the performance of the web page. In other words, it limits the rate at which a function gets invoked.

What is a debounce input?

In JavaScript, a debounce function makes sure that your code is only triggered once per user input. Search box suggestions, text-field auto-saves, and eliminating double-button clicks are all use cases for debounce.


1 Answers

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!"); })); 
like image 173
Geoff Avatar answered Sep 20 '22 16:09

Geoff