Subscribe to
Posts
Comments

UPDATED: 7/Feb/2011 with comments from Simon Smith.

I’ve seen a few examples of people trying to mimic the Google Instant search with their own solution. Most of these have just made them “instant” searches by changing

$("#searchButton").click(function(){
  ...perform actual search...
});

to

$("#searchButton").keyup(function(){
  ...perform actual search...
});

My gripe is that Instant doesn’t need to be, and in fact shouldn’t always be, Instant. There are 3 reasons for this

1) A lot of users type looking at their keyboard so Instant just needs to mean “ready when a user looks up from their keyboard to see the result”
2) Browser and network performance can be significantly harmed if you’re issuing complex javascript/ajax/network requests on every single keypress.

The solution? Well, my solution is very simple.

$(document).onready(function(){
   var _timerId = 0;

   $("searchButton").keyup(function(){
      window.clearTimeout(_timerId);
      _timerId = window.setTimeout(function() {
         ...perform actual search...
      }, 170);
   }).keydown(function(){
      window.clearTimeout(_timerId);
   });
});

In this example I set a timer which fires 170ms after the LAST keypress. It’s pretty imperceivable that there’s a delay at all, but it dramatically improves CPU/bandwidth performance of these “Instant” searches, and it still appears to be pretty Instant.