A search box that asks the server on every keystroke sends five requests for "react", and the answers can arrive out of order, so the results for "rea" may replace the results for "react". A good search box waits until the user pauses, skips requests that would change nothing, and ignores answers that are no longer the latest.
Write connectSearch(input, search, render, wait) in search.js. The page (index.html, read-only) wires it to a pretend fruit search so you can try it.
Listen for the input's input events. Each one restarts a wait of wait ms (300 when missing); nothing is searched while the user keeps typing.
When a whole wait passes, read the input's value and trim it. That is the query.
An empty query calls render([]) and does not search.
A query equal to the last query handled (including an empty one) does nothing.
Otherwise call search(query) once and render its results when they arrive, unless a newer query has been handled since; an older answer is then ignored. Clearing the box counts as a newer query.
A failed search renders nothing and causes no unhandled rejection; later searches still work.
disconnect() stops listening, cancels a waiting search, and makes answers still on their way stale.
Each call to connectSearch has its own timer and state.
constinput= document.querySelector("#search");connectSearch(input, (query) =>fetchResults(query), showResults);// The user types "r", "re", "rea" 100 ms apart, then stops:// one search for "rea", 300 ms after the last key.
JAVASCRIPT
// The user searches "lemon", then quickly types "lemons" and deletes the "s":// the query is "lemon" again, the same as the last one: no new request.
JAVASCRIPT
// "slow" is searched and takes 1 s; "fast" is searched 300 ms later and takes 50 ms.// render(["fast…"]) runs; the late answer for "slow" is ignored.
JAVASCRIPT
constdisconnect=connectSearch(input, search, render);disconnect(); // typing no longer searches, and nothing waiting will render
Plain JavaScript in a browser page; the tests call the global connectSearch from search.js.
The tests create their own inputs, type by setting value and dispatching an input event, and use a fake search on a virtual clock that replaces setTimeout and clearTimeout.
Showing a loading state, and cancelling the request itself with AbortController, are out of scope.