ajsie ajsie - 7 months ago 369
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

setTimeout
, but it didn't work.

How can I do that?

CMS CMS
Answer

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);
  };
})();

Usage:

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

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

Comments