31

How can I delay actions between keypress in jQuery. For example;

I have something like this

 if($(this).val().length > 1){
   $.post("stuff.php", {nStr: "" + $(this).val() + ""}, function(data){
    if(data.length > 0) {
      $('#suggestions').show();
      $('#autoSuggestionsList').html(data);
    }else{
      $('#suggestions').hide();
    }
 });
}

I want to prevent posting data if the user continously typing. So how can I give .5 seconds delay?

Sinan
  • 5,819
  • 11
  • 39
  • 66

5 Answers5

66

You can use jQuery's data abilities to do this, something like this:

$('#mySearch').keyup(function() {
  clearTimeout($.data(this, 'timer'));
  var wait = setTimeout(search, 500);
  $(this).data('timer', wait);
});

function search() {
  $.post("stuff.php", {nStr: "" + $('#mySearch').val() + ""}, function(data){
    if(data.length > 0) {
      $('#suggestions').show();
      $('#autoSuggestionsList').html(data);
    }else{
      $('#suggestions').hide();
    }
  });
}

The main advantage here is no global variables all over the place, and you could wrap this in an anonymous function in the setTimeout if you wanted, just trying to make the example as clean as possible.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
11

All you need to do is wrap your function in a timeout that gets reset when the user presses a key:

var ref;
var myfunc = function(){
   ref = null;
   //your code goes here
};
var wrapper = function(){
    window.clearTimeout(ref);
    ref = window.setTimeout(myfunc, 500);
}

Then simply invoke "wrapper" in your key event.

Jerod Venema
  • 44,124
  • 5
  • 66
  • 109
3

There is a nice plugin to handle this. jQuery Throttle / Debounce

PetersenDidIt
  • 25,562
  • 3
  • 67
  • 72
  • isn't there a jQuery dependency for everything? Have to admit- the name "Debounce" invokes cynical laughter! Anyway, good find. – C. Tewalt Aug 05 '15 at 21:36
  • lodash also has [throttle](https://lodash.com/docs#throttle) and [debounce](https://lodash.com/docs#debounce) methods – Jamie Humphries Aug 11 '15 at 10:37
2

Nick's answer is perfect but if handling first event immediately is critical then I think we can do:

$(selector).keyup(function(e){ //or another event

    if($(this).val().length > 1){
        if !($.data(this, 'bouncing-locked')) {

            $.data(this, 'bouncing-locked', true)

            $.post("stuff.php", {nStr: "" + $(this).val() + ""}, function(data){
                if(data.length > 0) {
                    $('#suggestions').show();
                    $('#autoSuggestionsList').html(data);
                }else{
                    $('#suggestions').hide();
                }
           });

            self = this
            setTimeout(function() {
                $.data(self, 'bouncing-locked', false);

                //in case the last event matters, be sure not to miss it
                $(this).trigger("keyup"); // call again the source event
            }, 500)
        }
    }
});
nicolallias
  • 1,055
  • 2
  • 22
  • 51
Huy Le
  • 657
  • 5
  • 17
1

I'd wrap it in a function like so:

  var needsDelay = false;

  function getSuggestions(var search)
  {
    if(!needsDelay)
    {
        needsDelay = true;
        setTimeout("needsDelay = false", 500);

        if($(this).val().length > 1){
            $.post("stuff.php", {nStr: "" + search + ""}, function(data){
                if(data.length > 0) {
                    $('#suggestions').show();
                    $('#autoSuggestionsList').html(data);
                }else{
                    $('#suggestions').hide();
                }
            });
        }
    }


  }

That way no matter how many times you ping this, you will never search more than every 500 milliseconds.

thaBadDawg
  • 5,160
  • 6
  • 35
  • 44
  • 5
    never pass a string to setTimeout! eval is evil (in *most* cases) :) use an anoymous function like: `setTimeout(function() { needsDelay = false; }, 500);` instead. – Nick Craver Mar 09 '10 at 17:16
  • I know that eval is evil, yet I still am lazy and put eval statements in my code. I need to add that to my nazi list. No more eval. – thaBadDawg Mar 09 '10 at 18:15