delaying actions between keypress in jQuery delaying actions between keypress in jQuery jquery jquery

delaying actions between keypress in jQuery


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.


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.