Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delaying actions between keypress in jQuery

Tags:

jquery

ajax

delay

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?

like image 438
Sinan Avatar asked Mar 09 '10 17:03

Sinan


1 Answers

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.

like image 88
Nick Craver Avatar answered Sep 18 '22 12:09

Nick Craver