ajsie ajsie - 5 months ago 206x
Javascript Question

jQuery .keyup() delay

I've got a search field.

Right now it searches for every keyup. So if someone types Windows, it will make a search with AJAX for every keypress: W, Wi, Win, Wind, Windo, Window, Windows.

I want to have a delay, so it only searches when the user stops typing for 200 ms.

There is no option for this in the keyup function, and I have tried

, but it didn't work.

How can I do that?


I use this function for the same purpose, executing a function after the user has stopped typing for a specified amount of time:

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);


$('input').keyup(function() {
      alert('Time elapsed!');
    }, 1000 );

For something more sophisticated, give a look to the jQuery Typewatch plugin.