Peter Olson Peter Olson - 5 months ago 36
Javascript Question

Throttle event calls in jQuery

I have a

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?


Take a look at jQuery Debounce.

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