When the page sends two requests, the answers don't have to come back in the same order. A search for m can be slow and arrive after the search for mug. The page draws each answer when it arrives, so the old answer would be drawn last, and the list would not match the search box.
The fix is to number the requests. A counter outside the function goes up by 1 on every call, and each call keeps its own number in a constant. When the answer arrives, the call compares the two: if a newer request has started in the meantime, this answer is old, and the call returns without drawing. Here is the idea on a details panel:
let detailsCount = 0;
async function showDetails(id) {
detailsCount += 1;
const mine = detailsCount;
const response = await fetch("/api/products/" + id);
if (mine !== detailsCount) return; // a newer click came after this one
// … read the JSON and draw the product
}
The starting code also lost a line from the last lesson: without clearTimeout, typing mug leaves three timers running and sends three requests. The check makes later requests answer first, types mug and lets 300 ms pass. Your page must show one request, and the search's answer:
> from now on, later requests are answered first > type "mug" into "Search" > 300 ms pass request: GET /api/products?q=mug -> 200 - text: 8 products + text: 1 products (the list keeps only "Mug $12")
Your task: count the searches in requestCount, keep each call's number in thisRequest, return without drawing when a newer search has started, and put clearTimeout(timer) back in the input listener.
Assignment
Follow the Coding Tutorial to number the searches in loadProducts, ignore any answer that is not the latest, and bring the debounce back.
HintrequestCount lives outside the function, so every call shares it; thisRequest is a const inside the function, so every call has its own. Compare them right after the fetch line: that is when time has passed.
Free plan: 30 tutor messages. PRO is unlimited.
