views:

1561

answers:

4

i have a search field where the user type in a search string and it searches.

right now it searches for every keyup. so if he types Windows it will make a search with ajax for every key he press. W, Wi, Win, Wind, Windo, Windows.

I want to have a delay instead, so it just search when he stops typing for 0.2s.

There is no option for this in the keyup function. and i have tried to have setTimeout without result. then it just delay for some secs and then it do a search for all the letters i typed in.

How can I do that?

A: 

Take a look at the autocomplete plugin. I know that it allows you to specify a delay or a minimum number of characters. Even if you don't end up using the plugin, looking through the code will give you some ideas on how to implement it yourself.

tvanfosson
+1  A: 

If you want to search after the type is done use a global variable to hold the timeout returned from your setTimout call and cancel it with a clearTimeout if it hasn't yet happend so that it won't fire the timeout except on the last keyup event

var globalTimeout = null;
$('#id').keyup(function(){
if(globalTimeout != null) clearTimeout(globalTimeout);
setTimeout(SearchFunc,200);
}
function SearchFunc(){
globalTimeout = null;
//ajax code }

RHicke
looks nice..i will save this one too in my snippet code!
weng
+1  A: 

Use

mytimeout = setTimeout( expression, timeout );

where expression is the script to run and timeout is the time to wait in milliseconds before it runs - this does NOT hault the script, but simply delays execution of that part until the timeout is done.

clearTimeout(mytimeout);

will reset/clear the timeout so it does not run the script in expression (like a cancel) as long as it has not yet been executed.

Mark Schultheiss
+11  A: 

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.

CMS
it worked as a charm and was easy to implement. thx!
weng
Another alternative: http://github.com/bgrins/bindWithDelay/blob/master/bindWithDelay.js. It pretty much works the same way you described, I just found myself using that pattern a lot so implemented it as a jQuery plugin to make the syntax simpler. Here is a demo page: http://briangrinstead.com/files/bindWithDelay/
Brian Grinstead