Today I Learned

This project exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any Rocketeer as well as selected friends of JetRockets. We hope you enjoy learning along with us.

Typeahead async requests throttling

As everybody else have some legacy code (who does not have it?), and yesterday we faced with problem.

Our internal app have search panel where users could write and get related results. But search was written with typeahead and without any throttling. So it’s triggered full text search on backend side on every input change which leads to DB connection pool exhaustion.

We didn’t found any ready to use solutions, so we added following fix:

    async: true
    source: (query, syncResults, asyncResults) ->
      href = self.href
      # Added getAsyncResults call to throttle requests:
        () ->
            url: href
              query: query
            dataType: 'json'
            (data, textStatus, jqXHR) ->

where getAsyncResults defined before typeahead init:

# throttle is lodash function
getAsyncResults = _.throttle(((fn) ->
  ), 300,
  { ... })

Would be happy if someone find this simple solution helpfull.

Looking for help? At JetRockets, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.