In the last lesson every key in the Search box asked the server: typing "mug" sent three requests, for m, mu and mug. The visitor only wanted the last one. Better: wait until the visitor pauses, and ask only when 300 ms pass with no new key. This is called debouncing.
Two timer functions do it. setTimeout(fn, ms) runs fn later and returns an id for that wait. clearTimeout(id) cancels the wait if it hasn't run yet:
const id = setTimeout(() => console.log("Hi"), 1000);
clearTimeout(id); // "Hi" is never printed
So each key cancels the wait the key before it started, then starts a fresh 300 ms wait. Only the last key's wait runs out. Keep the id in a variable declared once, outside the listener, so the next key can find it. The category select keeps asking right away: one pick is one event.
The check types "mu", lets 200 ms pass, types "g", then lets 200 ms and 100 ms pass. Your page must show:
> open the page
request: GET /api/products -> 200
text: 8 products
> type "mu" into "Search"
> 200 ms pass
screen: no change
> type "g" into "Search"
> 200 ms pass
screen: no change
> 100 ms pass
request: GET /api/products?q=mug -> 200
text: 1 products (only the Mug)
Your task: declare let timer;, then give search an input listener that cancels the old wait with clearTimeout(timer) and stores a new setTimeout that calls loadProducts after 300 ms.
Assignment
Follow the Coding Tutorial to make the Search box ask the API once, 300 ms after the last key.
Hint
Inside the listener, clearTimeout comes first and setTimeout second. clearTimeout with an empty timer does nothing, so the first key is fine.
Free plan: 30 tutor messages. PRO is unlimited.
