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

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


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}


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


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/