Peter Olson Peter Olson - 1 month ago 5
Javascript Question

Throttle event calls in jQuery

I have a

keyup
event bound to a function that takes about a quarter of a second to complete.

$("#search").keyup(function() {
//code that takes a little bit to complete
});


When a user types an entire word, or otherwise presses keys rapidly, the function will be called several times in succession and it will take a while for them all to complete.

Is there a way to throttle the event calls so that if there are several in rapid succession, it only triggers the one that was most recently called?

Answer

Take a look at jQuery Debounce.

$('#search').keyup($.debounce(function() {
    // Will only execute 300ms after the last keypress.
}, 300));
Comments