Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท Building AJAX User Interfaces

Live Search, Pagination and Infinite Scroll

Build search-as-you-type with debouncing, drop stale results with AbortController, and load long lists by page, offset, cursor or infinite scroll.

Two of the most common AJAX features answer the same question from opposite sides: "how do I show the user a small piece of a big collection?" A live search shows the matching pieces while the person is still typing. Pagination and infinite scroll show a list a few items at a time, so the page loads fast and the server does not send ten thousand rows nobody will read.

Both features are about timing. A search box can fire a request on every keystroke, and the answers can come back in a different order than the questions went out. A scroll listener can fire hundreds of times a second. Handling these well is the difference between an interface that feels instant and one that flickers, shows the wrong results or hammers the server.

The sandbox has no server, so the demos call a small mock API that waits a moment and returns real Response objects. It also understands an AbortSignal, like the real fetch(). In your own project you would replace it with fetch("/api/books?q=...").

Live search: debounce first

If you send a request for every keystroke, typing "javascript" makes ten requests, nine of which are obsolete before they finish. Debouncing waits until the user pauses typing (commonly 250 to 400 ms) and only then sends one request. Each new keystroke resets the timer.

JavaScript
function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

input.addEventListener("input", debounce(runSearch, 300));

Debouncing is different from throttling, which lets a function run at most once per interval. Use debounce for "wait until the user is done" (search, autosave, resize) and throttle for "keep up while it keeps happening" (scroll position).

The stale response problem

Debouncing reduces the number of requests, but it does not guarantee the order of answers. Suppose the user searches for "ja", pauses, types "jav" and pauses again. Two requests are in flight. If the server answers the second one first, the interface shows the "jav" results and then, when the slow "ja" answer arrives, replaces them with the wrong ones. This is a race condition, and it is one of the classic AJAX bugs.

The fix is to cancel the previous request when you start a new one. An AbortController gives you a signal to pass to fetch(); calling abort() makes the old promise reject with an AbortError, which you ignore because it is expected. The cancelling requests lesson covers the API in depth; here is how it fits into a search box:

sequenceDiagram
  participant U as User
  participant P as Page
  participant S as Server
  U->>P: types "ja"
  P->>S: GET q=ja
  U->>P: types "v" ("jav")
  P->>S: abort "ja", GET q=jav
  S-->>P: results for "jav"
  P-->>U: shows "jav" results

Each new search aborts the one before it, so only the latest answer can reach the screen.

The demo below combines both techniques. It also shows a count of requests that actually started and a count that were cancelled, so you can watch the effect. Type quickly, then slowly, and compare.

Debounced search with cancellation

A few more habits make a search box feel professional: trim the query, skip very short ones, show a "no results" message instead of an empty box, keep the old results visible (slightly dimmed) while new ones load instead of flashing a blank page, and escape or textContent everything you render (see rendering API data safely). Keep the search term in the URL (history.replaceState) if people may want to share or reload the page. Note that the sandbox forbids history changes, so that last tip is something to try in a real page.

Three ways to paginate

Whatever the interface, the API must support loading a slice of the collection. Three designs are common, and each has different strengths. REST conventions mention them; here they are side by side.

Style Request Good for Weakness
Page number ?page=3&per_page=20 Numbered page links, jumping to any page Items shift when the data changes between requests
Offset and limit ?offset=40&limit=20 Flexible slicing Deep offsets are slow on big tables; same shifting problem
Cursor ?after=abc123&limit=20 Infinite scroll, feeds that change constantly No jumping to page 7; you can only go forward or back

A cursor is an opaque token (often an encoded id or timestamp) that the server returns with each page: "to continue, send me this value". Because it points at a position in the data instead of counting from the top, new rows added at the front do not cause duplicates or skipped items on the next request. Never build cursors on the client; treat them as strings you pass back untouched.

A well-designed response says whether more data exists, so the client does not have to guess:

JSON
{
  "items": [ { "id": 41, "title": "..." } ],
  "next_cursor": "eyJpZCI6NDF9",
  "has_more": true
}

The next demo runs a mock API that supports all three styles. Compare what each request looks like and what comes back.

JS Page, offset and cursor pagination

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For classic numbered pagination, remember the interface details: disable the Previous and Next buttons at the ends, show a loading state while a page is fetched, keep the page number in the URL so the Back button works, and use the total count (when the API provides it) to render the page links.

Infinite scroll with IntersectionObserver

Infinite scroll loads the next page when the user nears the end of the list. The old way listened to the scroll event and measured positions on every call, which is slow. The modern tool is IntersectionObserver, which tells you when an element enters the viewport. Place an invisible sentinel element after the list; when it becomes visible, fetch the next page:

flowchart TD
  A["Sentinel scrolls into view"] --> B{"Already loading<br/>or no more data?"}
  B -->|"Yes"| C["Do nothing"]
  B -->|"No"| D["Fetch next page with cursor"]
  D --> E["Append items before the sentinel"]
  E --> F{"has_more?"}
  F -->|"Yes"| G["Keep observing"]
  F -->|"No"| H["Stop observing, show the end message"]

The guard at the top is what prevents duplicate requests while a page is still loading.

The demo uses a scrolling box with its own scrollbar as the root of the observer. Scroll to the bottom of the list. In a full page you would leave out root so that the browser viewport is used. The rootMargin of 100px starts loading slightly before the sentinel is actually visible, which hides the delay from the user.

Infinite scroll with a sentinel

Two cautions apply to every infinite list. First, it is hard to reach a footer, and the Back button may drop the user at the top of a list they spent minutes scrolling, so consider a visible "Load more" button as a fallback or as the only trigger. Second, very long lists keep every node in memory; for thousands of rows, look into virtual lists that render only what is visible. For accessibility, announce newly loaded content politely (for example with a status message such as "10 more items loaded") and make sure keyboard users can still reach everything.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does debouncing a search input do?

    A debounced function restarts its timer on each call and runs only after the calls stop for the chosen delay.
  2. 2. Why can a search box show the wrong results even with debouncing?

    Answers can arrive out of order. Abort the previous request (or ignore responses that are not for the latest query) to avoid this race condition.
  3. 3. What should you do with the AbortError thrown by an aborted request in a search handler?

    Aborting is a normal part of the flow. Check error.name === "AbortError" and return without touching the interface.
  4. 4. Why are cursors usually better than page numbers for a constantly changing feed?

    A page number counts from the top, so inserting rows shifts everything. A cursor marks where you stopped.
  5. 5. What is the job of the sentinel element in infinite scroll?

    The sentinel sits after the last item. When the observer reports it as visible, you load the next page. You still need a guard against duplicate loads.

Summary

  • Debounce search input so one request is sent after the user pauses; throttle is for continuous events like scrolling.
  • Abort the previous request when starting a new one, and ignore AbortError, to prevent stale results.
  • Handle short queries, loading, empty and error states in a search interface.
  • Page numbers and offsets suit numbered navigation; cursors suit feeds and infinite scroll. Treat cursors as opaque.
  • Use IntersectionObserver with a sentinel for infinite scroll, guard against double loading, and stop observing when the data ends.
  • Offer a "Load more" button or similar fallback for accessibility and long lists.

Next: XMLHttpRequest and Legacy AJAX shows the older API behind countless existing codebases and how to convert it to fetch.