Last Updated: February 25, 2016
·
435
· manudwarf

Dead-simple optimized and concurrency-safe search

While programming a searchbox, I was facing two problems :

  1. As AJAX stands for asynchronous and querying "A" takes more time than "AAA", be sure that what is displayed is well the latest query.
  2. As a guy who types really fast, be sure to not send X useless requests.

Turned out it was pretty simple to manage, without plugins or anything !

 Synchronousness problem

var input = $("#theInputSelector");
input.change(function() {
  var value = input.val();
  $.get("/the/url/to/call", function(data) {
    if (value != input.val()) {
      return;
    }
    doStuff();
  });
});

Just check the value when the AJAX callback is called. The result changed in our absence ? Forget it.
No queue, all queries are made and the correct one is kept.

 Don't send all

You don't want your server to receive :

/search/I
/search/I%20%
/search/I%20%j
/search/I%20%ju
/search/I%20%jus
/search/I%20%just

Well, again, same logic, and simple solution :

var input = $("#theInputSelector");
input.change(function() {
  var value = input.val();
  setTimeout(function() {
    if (value != input.val()) {
      return;
    }

    $.get("/the/url/to/call", function(data) {
      if (value != input.val()) {
        return;
      }
      doStuff();
    });
  }), 200);
});

200ms is a totally arbitrary choice, it is up to you to find a balance between getting blazing fast answers and DDOSing the server.

I you liked this, leave a tip on Flattr :)
<a href="http://flattr.com/thing/1375386/manudwarf-on-Coderwall" target="_blank">Flattr this</a>