[ACCEPTED]-How do I make my live jQuery search wait a second before performing the search?-ajax

Accepted answer
Score: 58

Easy, using setTimeout. Of course you only want one 2 timer going at once, so it's important to 1 use clearTimeout at the beginning of the function...

$(function() {
  var timer;
  $("#searchMe").keyup(function() {
    var ms = 200; // milliseconds
    var val = this.value;
    timer = setTimeout(function() {
    }, ms);
Score: 5

You may be interested in my bindDelayed jQuery mini-plugin. It:

  • Allows you to specify a delay before kicking off the request
  • Automatically cancels any previous requests that were scheduled to go off
  • Automatically cancels any in-air XHR requests that were in progress when you make your request
  • Only invokes your callback for the latest request
    • If the user types "s", waits long enough for the request to go out, and then types "a", and the response for "s" comes back before the response for "sa" you won't have to deal with it.

The 3 answer to the original question using bindDelayed would 2 look like so:

// Wait 200ms before sending a request,
// avoiding, cancelling, or ignoring previous requests
  // Construct the data to send with the search each time
  return {queryString:this.value};
  // Use the response, secure in the knowledge that this is the right response

In case my site is down, here's 1 the plugin code for Stack Overflow posterity:

  // Instructions: http://phrogz.net/jquery-bind-delayed-get
  // Copyright:    Gavin Kistner, !@phrogz.net
  // License:      http://phrogz.net/js/_ReuseLicense.txt
  $.fn.bindDelayed = function(event,delay,url,dataCallback,callback,dataType,action){
    var xhr, timer, ct=0;
    return this.on(event,function(){
      if (xhr) xhr.abort();
      timer = setTimeout(function(){
        var id = ++ct;
        xhr = $.ajax({
          data:dataCallback && dataCallback(),
            xhr = null;
            if (id==ct) callback.call(this,data);
Score: 3

You really ought to look at using the jQuery 5 autocomplete plugin. I find this plugin to be very 4 useful and it already does what you need. Look 3 particularly at the delay option, which you can 2 customize to change how long the plugin 1 waits after a keystroke to run.

Score: 1

1 solution in psuedocode:

    txt = getTxt
    newTxt = getTxt
    if (txt == newTxt)  // nothing has been typed so do something
       run my thing


Score: 1

this one is happy


   $("#searchMe").keyup(function () {

  timeoutID = window.setTimeout(run, 2000); //delay

  function run()
  {      //dowhatev
    var text = $("#searchMe").val();


More Related questions