AJAX: Delay for search on typing in form field [duplicate]

Solution 1:

var delayTimer;
function doSearch(text) {
    clearTimeout(delayTimer);
    delayTimer = setTimeout(function() {
        // Do the ajax stuff
    }, 1000); // Will do the ajax stuff after 1000 ms, or 1 s
}

Solution 2:

Simply setup the delayed invocation with setTimeout(), then remove it again on every event with clearTimeout()

HTML

<form action="" method="post" accept-charset="utf-8">
    <p><input type="text" name="q" id="q" value="" onkeyup="doDelayedSearch(this.value)" /></p>
</form>

Javascript

var timeout = null;

function doDelayedSearch(val) {
  if (timeout) {  
    clearTimeout(timeout);
  }
  timeout = setTimeout(function() {
     doSearch(val); //this is your existing function
  }, 2000);
}

Solution 3:

For this type of thing I tend to use a cunning little 'throttling' function created by Remy Sharp:

http://remysharp.com/2010/07/21/throttling-function-calls/