TIP: rate-limit your "instant-search" with a Future

20 views
Skip to first unread message

AJ ONeal

unread,
Oct 31, 2010, 4:51:51 AM10/31/10
to futures-j...@googlegroups.com
I'm creating an instant-search widget for an API that has a slow response time.

This demonstrates how to rate-limit such an instant search so that the search only occurs if a non-word character was entered (punctuation, etc) or if it has been 300ms since the last keystroke.


    var key_timeout = -1;
    function handleInstantSearchInput(ev) {
      ev.preventDefault();

      var promise = Futures.promise(),
       search = "";

      // clean the promise for the previous keypress
      clearTimeout(key_timeout);

      search = $('form#instant_search input').val();

      // TODO test unicode rather than ASCII
      if (!search.match(/\w$/) && search.length >= 5) {
          // if the search is at least 5 chars and ends in
          // a non-char (space, punctuation, etc)
          // the perform the search
          promise.fulfill(search);
      } else {
          // if the user doesn't keypress for 300 ms, search then
          key_timeout = setTimeout(promise.fulfill, 300, search);
      }

      promise.when(function (search) {
        // don't file now and then in 300ms
        clearTimeout(key_timeout);

        // This example is for the CampusBooks API using the AHR request object (also works in node)
        campusbooks.search({ title: search }).when(function (err, xhr, data) {
          if (err || data && data.repsonse && data.response.errors) {
            // search didn't match, perhaps display error
            return false;
          }
          if (data && 0 === data.response.page.results.length) {
            return false;
          }

          // suppose the template module has already been set up
          $("div#search_results").render(data, template);
        });
      });
    }
    $('body').delegate('form#instant_search', 'keyup', handleInstantSearchInput);
    $('body').delegate('form#instant_search', 'submit', handleInstantSearchInput);

AJ ONeal

John Finney

unread,
Feb 12, 2013, 8:31:53 AM2/12/13
to futures-j...@googlegroups.com
Why would you do this though? Can you explain please? Can you also explain the significance of 300ms?
Reply all
Reply to author
Forward
0 new messages