I have a web-based search input. At each onkeyup event, an async request is made, from the client with JavaScript, to a PHP document that returns the search response – then the JS takes the search response and writes it to the client. This part works fine.
However, my issue is when a user types their search term faster than the system can respond.
Let’s say a user – that types fast – is doing a search for the word super. The user types s (and a search is done for s), while the search is being performed and written for s the user types u, and now a search for su is queued up. Then, this very fast typing user types a p, while the initial search for s is finishing up, and now searches for su and sup are queued.
If a user types slowly, there is no issue and my search tool can respond to each keyup without having to queue up search requests. However, if a user types very fast, they will see several search result refreshes flash before them after they finish typing their search term because the script is finishing up items in the queue.
How could I improve my code to improve the user experience?
For example, how would you script this so that any queued items, other than the last one made are dropped?
You can do this with a single timeout (called debouncing):
This code means that if the user is typing too fast (delta <50ms in this case) the action won’t queue up, but the newest always overwrites the previous ones.
There is another approach (called throttling):
Finally you can fetch more data at a time to get around latency issues.
See this post to see how Flickr does it: Building Fast Client-side Searches
Also make sure to use some kind of caching (APC/memcache) depending on how frequently your data changes. This can greatly reduce stress on your database.