64

On my website I use JavaScript/AJAX to do the search and show results while the user is still typing.

HTML (body):

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

JavaScript (header):

function doSearch(text) {
    // do the ajax stuff here
    // call getResults.php?search=[text]
}

But this could cause a lot of requests coming to the server.

Thus I want to relieve the server by setting up a delay:

Whenever the onkeyup event is fired, the function doSearch() should show an "ajax loading graphic" and wait for 2 seconds. Only if the event is NOT fired again during these 2 seconds, the results should be fetched from the PHP file.

Is there any way to do this? Could you help me please? Thanks in advance!

caw
  • 30,999
  • 61
  • 181
  • 291
  • 6
    Technically, the question has not been asked before, but three years *after*. – caw Dec 24 '15 at 02:42

3 Answers3

172
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
}
Mike Richards
  • 5,557
  • 3
  • 28
  • 34
24

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);
}
Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46
  • 1
    Thank you! By the way I like that you kept to the separation and style of the code I chose. Makes it very easy for the questioner to make use of your answer ... – caw Oct 24 '11 at 18:27
5

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/

Andy Hume
  • 40,474
  • 10
  • 47
  • 58
  • 1
    Thank you very much! This throttling function is a really interesting thing. I really like that you can use it in every single use case. – caw Oct 24 '11 at 18:23