Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 334
Peter Olson Avatar asked Sep 10 '11 16:09

Peter Olson


People also ask

What is jQuery throttle Debounce?

jQuery throttle / debounce allows you to rate-limit your functions in multiple useful ways. 1k. (MIT OR GPL-2.0) licensed. Tags: jquery, throttle, debounce, ratelimit.

What is the difference between Debounce and throttle?

Throttle: the original function will be called at most once per specified period. Debounce: the original function will be called after the caller stops calling the decorated function after a specified period.

What is event throttling in JavaScript?

Throttling or sometimes is also called throttle function is a practice used in websites. Throttling is used to call a function after every millisecond or a particular interval of time only the first click is executed immediately.


3 Answers

Take a look at jQuery Debounce.

$('#search').keyup($.debounce(function() {
    // Will only execute 300ms after the last keypress.
}, 300));
like image 160
josh3736 Avatar answered Sep 28 '22 03:09

josh3736


Here is a potential solution that doesn't need a plugin. Use a boolean to decide whether to do the keyup callback, or skip over it.

var doingKeyup = false;

$('input').keyup(function(){
    if(!doingKeyup){
        doingKeyup=true;
        // slow process happens here
        doingKeyup=false;
    }
});
like image 41
Nathan Manousos Avatar answered Sep 28 '22 05:09

Nathan Manousos


You could also use the excellent Underscore/_ library.

Comments in Josh's answer, currently the most popular, debate whether you should really throttle the calls, or if a debouncer is what you want. The difference is a bit subtle, but Underscore has both: _.debounce(function, wait, [immediate]) and _.throttle(function, wait, [options]).

If you're not already using Underscore, check it out. It can make your JavaScript much cleaner, and is lightweight enough to give most library haters pause.

like image 25
Michael Scheper Avatar answered Sep 28 '22 04:09

Michael Scheper