Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Async Patterns for Requests

Caching and Polling

Cache API responses in memory, understand HTTP cache headers and ETag, poll for updates without waste, pause when the tab is hidden, and use stale-while-revalidate.

The fastest request is the one you never send. Many pieces of data change rarely: a list of countries, a user's profile, yesterday's report. Asking the server again on every click wastes time and bandwidth. On the other side, some data does change while the page is open, such as a build status or a message count, and the page must find out without a reload.

This lesson covers both halves: caching (reuse answers you already have) and polling (ask again on a schedule). You will build an in-memory cache with a time limit, learn how HTTP caching and ETag work, write a polling loop that behaves politely, and combine both ideas in the stale-while-revalidate pattern.

Where caches live

A response can be cached at several layers, each controlled differently:

flowchart LR
    P["Your page code<br/>(in-memory cache)"] --> B["Browser HTTP cache"]
    B --> C["CDN or proxy"]
    C --> S["Origin server"]

A request travels from your own cache to the browser cache, then a CDN, and only then to the server.

The browser cache and CDNs obey HTTP headers that the server sends. The in-memory cache is yours: it lives in a JavaScript variable and disappears when the page reloads. It is the simplest to reason about, so we start there.

An in-memory cache with a time limit

The idea: remember each response together with the time it was stored. If the entry is younger than its TTL (time to live), return it. Otherwise fetch again.

A second trick matters just as much: store the promise, not only the result. If two parts of the page ask for the same URL at the same moment, they share one request instead of sending two. This is called deduplicating in-flight requests.

JS A cache with TTL and shared in-flight requests

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

No output.

Two things to notice. The clock is a parameter, which lets the example jump forward in time instead of waiting. And a failed request removes itself from the cache, so one network error does not stay cached for a whole minute.

An in-memory cache can show stale or wrong data. Do not cache anything user-specific in a shared structure, and clear the cache after a write (a POST, PUT or DELETE to the same resource) so the user sees their own change.

HTTP caching headers

Servers steer the browser's own cache with response headers. fetch() uses this cache automatically, so well-chosen headers speed up your app without any JavaScript.

Header Example Meaning
Cache-Control: max-age max-age=3600 Reuse the response for one hour without asking
Cache-Control: no-cache no-cache You may store it, but check with the server before each reuse
Cache-Control: no-store no-store Do not store it at all (private or sensitive data)
ETag "v7" A fingerprint of this version of the resource
Last-Modified a date When the resource last changed

Conditional requests and ETag

When a cached copy has expired, the browser does not have to download the body again. It asks a yes-or-no question using the stored ETag, and the server answers with a tiny 304 Not Modified if nothing changed. This exchange needs a real server, so here it is as a read-only illustration:

HTTP
GET /api/report HTTP/1.1
If-None-Match: "v7"

HTTP/1.1 304 Not Modified
ETag: "v7"
sequenceDiagram
    participant B as Browser
    participant S as Server
    B->>S: GET /api/report
    S-->>B: 200 with body and ETag "v7"
    Note over B: later, cache expired
    B->>S: GET /api/report with If-None-Match "v7"
    S-->>B: 304 Not Modified (no body)
    Note over B: reuse the stored body

A 304 response means "your copy is still good" and saves the cost of sending the body again.

You can steer fetch() per call with the cache option, for example fetch(url, { cache: "no-store" }) to bypass the cache, or "force-cache" to prefer a stored copy. Most of the time the default is right, and the server's headers do the work.

Polling for updates

Polling means repeating a request on a timer to see whether something changed. It is simple and works everywhere, which is why it remains common for job status and notification counts. For a comparison with push-based alternatives see Streaming and Real-Time APIs.

Prefer setTimeout() scheduled after the previous request finishes over setInterval(). With an interval, a slow response can overlap the next tick and requests pile up. Also stop polling once the data you wait for is final.

JS Polling a job until it is done

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

No output.

The loop waits for each answer, schedules the next one, and ends by itself when the job is done. It returns a stop function so the owner can cancel it, for example when the user leaves the page.

Visibility-aware polling

A tab in the background does not need fresh data every few seconds, and thousands of hidden tabs polling add real server load. The Page Visibility API gives document.visibilityState ("visible" or "hidden") and a visibilitychange event. A polite poller pauses when hidden and refreshes immediately when the user comes back. In the sandbox we cannot hide a tab, so this demo uses a small fake page object with the same shape:

JS Pause polling while the tab is hidden

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

No output.

In a real page, replace fakePage with document. Pair this with a longer interval after repeated unchanged results, or with backoff when requests fail (see Retries, Backoff and Resilience).

Stale-while-revalidate

Users prefer an instant, slightly old answer over a spinner. Stale-while-revalidate returns the cached value immediately, then fetches a fresh one in the background and updates the screen when it arrives. The pattern also exists as an HTTP header, Cache-Control: stale-while-revalidate=60, and many data libraries are built around it.

JS Show cached data first, then refresh

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

No output.

On the first visit the user waits for the network. On the second, the cached list appears instantly and is replaced as soon as the fresh one arrives. Only use this for data where a few seconds of staleness is acceptable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why cache the promise instead of only the finished result?

    Storing the promise means the second caller gets the same pending request, so the server is hit once.
  2. 2. What does a 304 Not Modified response tell the browser?

    After a conditional request with If-None-Match or If-Modified-Since, a 304 saves downloading the body again.
  3. 3. Which is usually better for polling: setInterval or a setTimeout scheduled after each response?

    Scheduling the next request after the previous one finishes avoids overlapping requests when the server is slow.
  4. 4. What does stale-while-revalidate do?

    The user sees the old value immediately and the page updates when the fresh response arrives.
  5. 5. Which Cache-Control value is right for sensitive account data that must never be stored?

    no-store tells browsers and proxies not to keep a copy at all.

Summary

  • Cache in memory with a TTL, store promises to deduplicate in-flight requests, and clear entries after writes.
  • HTTP headers (Cache-Control, ETag) let the browser cache and revalidate with cheap 304 responses.
  • Poll with setTimeout after each response, stop when the data is final, and pause while the tab is hidden.
  • Stale-while-revalidate shows cached data instantly and refreshes it in the background.

Next: Rendering API Data in the DOM.