- Avoid sending too many requests in a short period. When using rate-limited services like the GitHub API, sending frequent requests can cause errors.
- Accommodate users who prefer reduced UI motion. As-you-type search results can change the UI rapidly.
- Anticipate typing speed. By carefully selecting an appropriate debounce delay for your audience, you can significantly reduce the number of search requests while maintaining a good user experience.
Write a debouncing function
To tell Autocomplete to “wait” for a set time after typing stops before returning results, write a debouncing function that returns a promise. When the timeout elapses, the promise for the passed items is resolved.JavaScript
debouncePromise
function lets you create a wrapper around any asynchronous function and delay it for a specified time:
200 ms in the example.
JavaScript
Select a debounce delay
The optimal debouncing delay should match your audience’s typing speed (typically 30 words per minute (WPM) on mobile devices and 40 WPM on desktop devices). If the delay is too short, users still see flashes of content. If the delay is too long, the time between key presses and results becomes too long. 200 ms is the preferred debounce delay. Delays of over 300 ms will start degrading the user experience. You should also increase thestallThreshold
setting to avoid showing a “loading” spinner after the final keystroke.
Set it to your debounce delay plus 300 ms.
Debounce sources
Use thedebounced
function for static and dynamic sources.
JavaScript