← Back to the journal

The Hidden Problem With Using setInterval() in JavaScript

That innocent-looking timer could be responsible for overlapping API requests, unexpected race conditions, and unnecessary server load.

On this page

The Hidden Problem With Using setInterval() in JavaScript

Reading position1 / 15
Editorial illustration for The Hidden Problem With Using setInterval() in JavaScript
AI-generated editorial illustration

If you've ever built a dashboard, a notification system, a live price tracker, or an application that periodically checks for updates, you've probably written something like this:

setInterval(async () => {
  const response = await fetch("/api/status");
  const data = await response.json();

  updateDashboard(data);
}, 5000);

Every five seconds, the application retrieves the latest information and updates the dashboard.

Simple enough.

The code is readable, requires no external dependencies, and works perfectly well when the API responds quickly.

But what happens when the server takes eight seconds to respond?

Or when the user's internet connection becomes unstable?

Or when the database suddenly starts responding more slowly than usual?

The behaviour of setInterval() under these conditions might not be what you expect.

The problem isn't necessarily with the timer itself. It's with the assumption that one asynchronous operation will finish before the next one begins.

And that assumption can introduce several problems into an otherwise well-written JavaScript application.

1. setInterval() doesn't wait for asynchronous operations to finish

One of the biggest misconceptions about setInterval() is that it waits for its callback to complete, including any asynchronous work, before scheduling another execution.

It doesn't.

Consider the following example. You can run it directly in your browser's developer console or a modern Node.js environment.

const sleep = ms =>
  new Promise(resolve => setTimeout(resolve, ms));

let requestId = 0;

const timer = setInterval(async () => {
  const id = ++requestId;

  console.log(`Request ${id} started`);

  await sleep(8000);

  console.log(`Request ${id} completed`);
}, 5000);

// Stop scheduling new requests after 16 seconds
setTimeout(() => clearInterval(timer), 16000);

The interval is five seconds, but each simulated request takes eight seconds to complete.

The approximate output is:

[05s] Request 1 started
[10s] Request 2 started
[13s] Request 1 completed
[15s] Request 3 started
[18s] Request 2 completed
[23s] Request 3 completed

Notice that Request 2 starts before Request 1 finishes.

The same thing happens with Request 3.

Overlapping asynchronous requests with setInterval. Requests start every five seconds and take eight seconds to finish, creating overlapping periods.
Requests start every five seconds and take eight seconds to finish, creating overlapping periods.
SVG source
<svg xmlns="http://www.w3.org/2000/svg"
     id="bw-interval-overlap"
     viewBox="0 0 760 340"
     width="760" height="340"
     role="img" aria-labelledby="bw-interval-overlap-title"
     aria-describedby="bw-interval-overlap-desc">

  <title id="bw-interval-overlap-title">
    Overlapping asynchronous requests with setInterval
  </title>
  <desc id="bw-interval-overlap-desc">Requests start every five seconds and take eight seconds to finish, creating overlapping periods.</desc>

  <style>
    #bw-interval-overlap [fill="#111111"] { fill: #ffffff; }
    #bw-interval-overlap [fill="#eeeeee"] { fill: #0f172a; }
    #bw-interval-overlap [fill="#aaaaaa"] { fill: #64748b; }
    #bw-interval-overlap [fill="#cccccc"] { fill: #475569; }
    #bw-interval-overlap [stroke="#444444"] { stroke: #cbd5e1; }
  </style>

  <rect width="760" height="340" rx="12" fill="#111111"/>

  <g font-family="Arial, Helvetica, sans-serif">

    <text x="24" y="35" font-size="20"
          font-weight="600" fill="#eeeeee">
      Overlapping asynchronous requests
    </text>

    <text x="24" y="58" font-size="13" fill="#aaaaaa">
      Interval: 5 seconds | Request duration: 8 seconds
    </text>

    <!-- Highlight overlapping periods -->
    <rect x="360" y="78" width="72" height="184"
          fill="#ef4444" opacity="0.12"/>

    <rect x="480" y="78" width="72" height="184"
          fill="#ef4444" opacity="0.12"/>

    <!-- Timeline grid -->
    <g stroke="#444444" stroke-dasharray="5 5">
      <path d="M120 78 V262"/>
      <path d="M240 78 V262"/>
      <path d="M360 78 V262"/>
      <path d="M480 78 V262"/>
      <path d="M600 78 V262"/>
      <path d="M720 78 V262"/>
    </g>

    <!-- Request labels -->
    <g fill="#eeeeee" font-size="15">
      <text x="24" y="123">Request 1</text>
      <text x="24" y="183">Request 2</text>
      <text x="24" y="243">Request 3</text>
    </g>

    <!-- Request bars -->
    <g fill="#2563eb">
      <rect x="240" y="100" width="192" height="36" rx="6"/>
      <rect x="360" y="160" width="192" height="36" rx="6"/>
      <rect x="480" y="220" width="192" height="36" rx="6"/>
    </g>

    <!-- Request duration -->
    <g fill="#ffffff" font-size="14" text-anchor="middle">
      <text x="336" y="123">8 seconds</text>
      <text x="456" y="183">8 seconds</text>
      <text x="576" y="243">8 seconds</text>
    </g>

    <!-- Timeline labels -->
    <g fill="#cccccc" font-size="13" text-anchor="middle">
      <text x="120" y="283">0s</text>
      <text x="240" y="283">5s</text>
      <text x="360" y="283">10s</text>
      <text x="480" y="283">15s</text>
      <text x="600" y="283">20s</text>
      <text x="720" y="283">25s</text>
    </g>

    <!-- Legend -->
    <rect x="24" y="307" width="16" height="12"
          rx="3" fill="#ef4444" opacity="0.5"/>

    <text x="49" y="318" font-size="13" fill="#cccccc">
      Overlapping request periods
    </text>

  </g>
</svg>
Download SVG

Overlapping asynchronous requests

Illustrative timeline: a five-second interval starts new requests while earlier eight-second requests are still running.

JavaScript isn't necessarily executing multiple pieces of JavaScript code simultaneously on the same thread. Instead, multiple asynchronous operations are outstanding concurrently.

When an async callback reaches an await, it can yield control back to the runtime. The timer mechanism doesn't wait for the promise returned by that callback to settle.

This behaviour follows the timer scheduling mechanism described in the WHATWG HTML Standard. MDN also specifically recommends considering recursive setTimeout() for polling operations that may take longer than their configured interval. 

html.spec.whatwg.org+1

The distinction matters because adding async to a callback doesn't turn setInterval() into an asynchronous task scheduler that understands when your work is finished.

2. Older responses can overwrite newer data

Overlapping requests aren't necessarily a problem on their own.

The bigger issue is what can happen when those requests complete in a different order from the one in which they started.

Imagine you're building a live cryptocurrency price dashboard.

Your application requests a price update every five seconds.

RequestStartedCompletedReturned price
Request A5s13s$100
Request B10s11s$105

In this hypothetical example, Request A retrieves an older snapshot but experiences a delayed response. Request B retrieves a newer snapshot and completes more quickly.

Your application first displays $105.

Two seconds later, Request A completes and overwrites the displayed price with $100.

The dashboard has gone backwards in time.

Stale API response overwrites newer data. Request B returns a newer price of $105 at eleven seconds. Request A returns an older price of $100 at thirteen seconds and overwrites it.
Request B returns a newer price of $105 at eleven seconds. Request A returns an older price of $100 at thirteen seconds and overwrites it.
SVG source
<svg xmlns="http://www.w3.org/2000/svg"
     id="bw-stale-response"
     viewBox="0 0 760 390"
     width="760" height="390"
     role="img" aria-labelledby="bw-stale-response-title"
     aria-describedby="bw-stale-response-desc">

  <title id="bw-stale-response-title">
    Stale API response overwrites newer data
  </title>
  <desc id="bw-stale-response-desc">Request B returns a newer price of $105 at eleven seconds. Request A returns an older price of $100 at thirteen seconds and overwrites it.</desc>

  <style>
    #bw-stale-response [fill="#111111"] { fill: #ffffff; }
    #bw-stale-response [fill="#eeeeee"] { fill: #0f172a; }
    #bw-stale-response [fill="#cccccc"] { fill: #475569; }
    #bw-stale-response [fill="#aaaaaa"] { fill: #64748b; }
    #bw-stale-response [stroke="#444444"] { stroke: #cbd5e1; }
    #bw-stale-response [stroke="#888888"] { stroke: #64748b; }
    #bw-stale-response [fill="#16a34a"],
    #bw-stale-response [fill="#4ade80"] { fill: #15803d; }
    #bw-stale-response [fill="#14291e"] { fill: #f0fdf4; }
    #bw-stale-response [stroke="#23833b"] { stroke: #86efac; }
    #bw-stale-response [fill="#301919"] { fill: #fef2f2; }
    #bw-stale-response [stroke="#dc2626"] { stroke: #fca5a5; }
    #bw-stale-response [fill="#f87171"] { fill: #b91c1c; }
  </style>

  <rect width="760" height="390" rx="12" fill="#111111"/>

  <g font-family="Arial, Helvetica, sans-serif">

    <text x="24" y="35" font-size="20"
          font-weight="600" fill="#eeeeee">
      When older responses arrive last
    </text>

    <!-- Timeline grid -->
    <g stroke="#444444" stroke-dasharray="5 5">
      <path d="M140 65 V200"/>
      <path d="M256 65 V200"/>
      <path d="M372 65 V200"/>
      <path d="M488 65 V200"/>
      <path d="M604 65 V200"/>
      <path d="M720 65 V200"/>
    </g>

    <!-- Request A -->
    <text x="24" y="108" font-size="15" fill="#eeeeee">
      Request A
    </text>

    <rect x="140" y="82" width="464" height="40"
          rx="6" fill="#b45309"/>

    <text x="372" y="107" text-anchor="middle"
          font-size="15" fill="#ffffff">
      Older snapshot: $100
    </text>

    <!-- Request B -->
    <text x="24" y="168" font-size="15" fill="#eeeeee">
      Request B
    </text>

    <rect x="430" y="142" width="58" height="40"
          rx="6" fill="#16a34a"/>

    <text x="499" y="168" font-size="15" fill="#4ade80">
      $105
    </text>

    <!-- Timeline labels -->
    <g fill="#cccccc" font-size="13" text-anchor="middle">
      <text x="140" y="220">5s</text>
      <text x="256" y="220">7s</text>
      <text x="372" y="220">9s</text>
      <text x="488" y="220">11s</text>
      <text x="604" y="220">13s</text>
      <text x="720" y="220">15s</text>
    </g>

    <!-- Latest result -->
    <rect x="24" y="248" width="320" height="100"
          rx="10" fill="#14291e" stroke="#23833b"/>

    <text x="184" y="275" text-anchor="middle"
          font-size="14" fill="#cccccc">
      11s — Newer response received
    </text>

    <text x="184" y="322" text-anchor="middle"
          font-size="34" font-weight="600" fill="#4ade80">
      $105
    </text>

    <!-- Connector -->
    <path d="M355 298 H405 M395 289 L405 298 L395 307"
          stroke="#888888" stroke-width="2" fill="none"/>

    <!-- Stale result -->
    <rect x="416" y="248" width="320" height="100"
          rx="10" fill="#301919" stroke="#dc2626"/>

    <text x="576" y="275" text-anchor="middle"
          font-size="14" fill="#cccccc">
      13s — Stale response overwrites data
    </text>

    <text x="576" y="322" text-anchor="middle"
          font-size="34" font-weight="600" fill="#f87171">
      $100
    </text>

    <text x="380" y="374" text-anchor="middle"
          font-size="13" fill="#aaaaaa">
      A response arriving later does not necessarily contain newer data.
    </text>

  </g>
</svg>
Download SVG

A delayed response can overwrite data that arrived from a more recent request.

This is a form of race condition.

You can encounter similar problems in search results, live order tracking, notification counters, monitoring dashboards, and collaborative applications.

One possible solution is to track the order in which requests were initiated.

let latestAppliedRequest = 0;
let requestId = 0;

setInterval(async () => {
  const id = ++requestId;

  try {
    const response = await fetch("/api/price");

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const data = await response.json();

    if (id < latestAppliedRequest) {
      return;
    }

    latestAppliedRequest = id;

    updatePrice(data.price);
  } catch (error) {
    console.error(error);
  }
}, 5000);

Now, a response from an earlier request cannot overwrite a successfully applied response from a later request.

However, this doesn't prevent overlapping requests. It only prevents one particular kind of stale update.

Also, request order doesn't necessarily guarantee actual data freshness. If the API provides a reliable version number or timestamp, comparing those values may be more appropriate.

For ordinary polling, we can often solve the underlying problem more directly.

3. Your application can unintentionally overload its own backend

Let's assume you're monitoring a service using a dashboard that makes an API request every two seconds.

Under normal conditions, the API responds in 200 milliseconds.

Everything looks fine.

Then the database experiences a slowdown, and each request starts taking ten seconds to complete.

Your frontend continues sending requests every two seconds, regardless of how many previous requests remain outstanding.

With enough connected users, the effects can become significant.

Consider this illustrative workload:

MetricNormal conditionsSlow backend
Connected dashboards1,0001,000
Polling interval2 seconds2 seconds
Requests initiated per second500500
Average request duration0.2 seconds10 seconds
Estimated outstanding requests1005,000

These are theoretical steady-state estimates, not measured benchmarks. They assume a stable request arrival rate and average response time, without cancellations or other limiting mechanisms.

The interesting part is that the request initiation rate hasn't changed.

The number of outstanding requests has.

Under the simplified assumptions above, we now have roughly 50 times as many outstanding operations competing for resources.

If the server is already struggling, this additional pressure can make things worse.

Database connections remain occupied for longer, memory usage may increase, requests may queue up, and response times may deteriorate further.

This is why polling deserves more consideration than simply choosing an interval.

A frontend timer can have backend architectural consequences.

4. A better alternative: recursive setTimeout()

Instead of scheduling a new operation every five seconds, what if we waited five seconds after the previous operation finished?

That small change makes a significant difference.

async function poll() {
  try {
    const response = await fetch("/api/status");

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const data = await response.json();

    updateDashboard(data);
  } catch (error) {
    console.error("Polling failed:", error);
  } finally {
    setTimeout(poll, 5000);
  }
}

poll();

Unlike our original setInterval() implementation, the next execution isn't scheduled until the current operation has finished.

The finally block ensures that polling continues even if an operation fails.

Let's compare both approaches, assuming each request takes eight seconds and both implementations start their first request immediately.

Fixed interval vs. completion-based polling

Fixed interval versus completion-based polling. Both examples start immediately. Fixed-interval requests overlap because eight-second tasks start every five seconds. Completion-based polling waits five seconds after each task finishes.
Both examples start immediately. Fixed-interval requests overlap because eight-second tasks start every five seconds. Completion-based polling waits five seconds after each task finishes.
SVG source

<svg xmlns="http://www.w3.org/2000/svg"
     id="bw-polling-comparison"
     viewBox="0 0 760 440"
     width="760"
     height="440"
     role="img"
     aria-labelledby="bw-polling-comparison-title"
     aria-describedby="bw-polling-comparison-desc">

  <title id="bw-polling-comparison-title">Fixed interval versus completion-based polling</title>
  <desc id="bw-polling-comparison-desc">Both examples start immediately. Fixed-interval requests overlap because eight-second tasks start every five seconds. Completion-based polling waits five seconds after each task finishes.</desc>

  <style>
    #bw-polling-comparison [fill="#111111"] { fill: #ffffff; }
    #bw-polling-comparison [fill="#eeeeee"] { fill: #0f172a; }
    #bw-polling-comparison [fill="#cccccc"],
    #bw-polling-comparison [fill="#bbbbbb"] { fill: #475569; }
    #bw-polling-comparison [fill="#aaaaaa"] { fill: #64748b; }
    #bw-polling-comparison [fill="#292929"] { fill: #f1f5f9; }
    #bw-polling-comparison [stroke="#444444"] { stroke: #cbd5e1; }
    #bw-polling-comparison [stroke="#333333"] { stroke: #e2e8f0; }
    #bw-polling-comparison [fill="#f87171"] { fill: #b91c1c; }
    #bw-polling-comparison [fill="#4ade80"] { fill: #15803d; }
  </style>

  <!-- Background -->
  <rect width="760" height="440" rx="12" fill="#111111"/>

  <!-- Section 1: Fixed interval -->
  <text x="24" y="35"
        font-family="Arial, Helvetica, sans-serif"
        font-size="19"
        font-weight="600"
        fill="#eeeeee">
    setInterval() — every 5 seconds
  </text>

  <!-- Upper timeline grid -->
  <line x1="120" y1="54" x2="120" y2="174"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="220" y1="54" x2="220" y2="174"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="320" y1="54" x2="320" y2="174"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="420" y1="54" x2="420" y2="174"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="520" y1="54" x2="520" y2="174"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="620" y1="54" x2="620" y2="174"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="720" y1="54" x2="720" y2="174"
        stroke="#444444" stroke-dasharray="5 5"/>

  <!-- Highlight overlapping time ranges -->
  <rect x="220" y="54" width="60" height="120"
        fill="#ef4444" opacity="0.12"/>

  <rect x="320" y="54" width="60" height="120"
        fill="#ef4444" opacity="0.12"/>

  <!-- Request labels -->
  <text x="24" y="82"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" fill="#cccccc">
    Request 1
  </text>

  <text x="24" y="122"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" fill="#cccccc">
    Request 2
  </text>

  <text x="24" y="162"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" fill="#cccccc">
    Request 3
  </text>

  <!-- Overlapping request bars -->
  <rect x="120" y="62" width="160" height="30"
        rx="5" fill="#b91c1c"/>

  <rect x="220" y="102" width="160" height="30"
        rx="5" fill="#b91c1c"/>

  <rect x="320" y="142" width="160" height="30"
        rx="5" fill="#b91c1c"/>

  <!-- Request duration labels -->
  <text x="200" y="82"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#ffffff">8s</text>

  <text x="300" y="122"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#ffffff">8s</text>

  <text x="400" y="162"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#ffffff">8s</text>

  <!-- Upper timeline axis -->
  <text x="120" y="195"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">0s</text>

  <text x="220" y="195"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">5s</text>

  <text x="320" y="195"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">10s</text>

  <text x="420" y="195"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">15s</text>

  <text x="520" y="195"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">20s</text>

  <text x="620" y="195"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">25s</text>

  <text x="720" y="195"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">30s</text>

  <!-- Upper section status -->
  <text x="720" y="219"
        font-family="Arial, Helvetica, sans-serif"
        font-size="14" text-anchor="end"
        fill="#f87171">
    Requests overlap
  </text>

  <!-- Section divider -->
  <line x1="24" y1="235" x2="736" y2="235"
        stroke="#333333" stroke-width="1"/>

  <!-- Section 2: Completion-based polling -->
  <text x="24" y="267"
        font-family="Arial, Helvetica, sans-serif"
        font-size="19" font-weight="600"
        fill="#eeeeee">
    Recursive setTimeout() — wait after completion
  </text>

  <!-- Lower timeline grid -->
  <line x1="120" y1="282" x2="120" y2="350"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="220" y1="282" x2="220" y2="350"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="320" y1="282" x2="320" y2="350"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="420" y1="282" x2="420" y2="350"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="520" y1="282" x2="520" y2="350"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="620" y1="282" x2="620" y2="350"
        stroke="#444444" stroke-dasharray="5 5"/>

  <line x1="720" y1="282" x2="720" y2="350"
        stroke="#444444" stroke-dasharray="5 5"/>

  <!-- Request row label -->
  <text x="24" y="324"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" fill="#cccccc">
    Requests
  </text>

  <!-- First request: 0s to 8s -->
  <rect x="120" y="300" width="160" height="36"
        rx="5" fill="#15803d"/>

  <!-- First waiting period: 8s to 13s -->
  <rect x="280" y="300" width="100" height="36"
        rx="5" fill="#292929"/>

  <!-- Second request: 13s to 21s -->
  <rect x="380" y="300" width="160" height="36"
        rx="5" fill="#15803d"/>

  <!-- Second waiting period: 21s to 26s -->
  <rect x="540" y="300" width="100" height="36"
        rx="5" fill="#292929"/>

  <!-- Third request: starts at 26s, visible until 30s -->
  <rect x="640" y="300" width="80" height="36"
        rx="5" fill="#15803d"/>

  <!-- Request and waiting period labels -->
  <text x="200" y="323"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#ffffff">8s</text>

  <text x="330" y="323"
        font-family="Arial, Helvetica, sans-serif"
        font-size="12" text-anchor="middle"
        fill="#bbbbbb">Wait 5s</text>

  <text x="460" y="323"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#ffffff">8s</text>

  <text x="590" y="323"
        font-family="Arial, Helvetica, sans-serif"
        font-size="12" text-anchor="middle"
        fill="#bbbbbb">Wait 5s</text>

  <text x="680" y="323"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#ffffff">8s task</text>

  <!-- Lower timeline axis -->
  <text x="120" y="370"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">0s</text>

  <text x="220" y="370"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">5s</text>

  <text x="320" y="370"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">10s</text>

  <text x="420" y="370"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">15s</text>

  <text x="520" y="370"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">20s</text>

  <text x="620" y="370"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">25s</text>

  <text x="720" y="370"
        font-family="Arial, Helvetica, sans-serif"
        font-size="13" text-anchor="middle"
        fill="#cccccc">30s</text>

  <!-- Lower section status -->
  <text x="720" y="397"
        font-family="Arial, Helvetica, sans-serif"
        font-size="14" text-anchor="end"
        fill="#4ade80">
    No overlapping requests
  </text>

  <!-- Footer caption -->
  <text x="24" y="424"
        font-family="Arial, Helvetica, sans-serif"
        font-size="12" fill="#aaaaaa">
    Both examples start immediately. The final task extends beyond the chart.
  </text>

</svg>
Download SVG

Completion-based polling naturally slows down when the underlying service takes longer to respond.

There is an important trade-off here.

With setInterval(), we attempt to start a new request every five seconds.

With recursive setTimeout(), the actual time between request starts becomes:

Request duration + Configured delay

An eight-second request followed by a five-second delay means the next request starts approximately thirteen seconds later.

For dashboards, status monitoring, and many background synchronisation tasks, that's often a reasonable trade-off.

The slower the server becomes, the less frequently each client sends requests.

We've introduced a simple form of client-side backpressure without installing another dependency.

Of course, this particular implementation continues polling indefinitely. We'll address cancellation shortly.

5. What if we still want a fixed polling interval?

Sometimes, waiting five seconds after every completed request isn't what we want.

Perhaps we want to attempt an update every five seconds, but skip the update if a previous request is still running.

In that case, we can keep setInterval() and introduce a simple execution guard.

let isRunning = false;

const timer = setInterval(async () => {
  if (isRunning) {
    return;
  }

  isRunning = true;

  try {
    const response = await fetch("/api/status");

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const data = await response.json();

    updateDashboard(data);
  } catch (error) {
    console.error(error);
  } finally {
    isRunning = false;
  }
}, 5000);

The timer still attempts to execute every five seconds.

However, if the previous operation hasn't finished, the current tick is skipped.

Assuming each request takes eight seconds:

05s — Request 1 started
10s — Skipped (request still running)
13s — Request 1 completed
15s — Request 2 started
20s — Skipped (request still running)
23s — Request 2 completed
25s — Request 3 started

This approach is particularly useful for periodic maintenance tasks, status monitoring, and operations where missing an individual execution is acceptable.

The finally block is important. Without it, a failed request could leave isRunning permanently set to true, effectively disabling all subsequent polling.

There is also a limitation: this guard only protects a single running JavaScript instance.

If your backend runs across multiple Docker containers or server processes, each instance has its own isRunningvariable. Preventing duplicate execution across distributed systems requires a different coordination mechanism.

6. Stopping a timer doesn't cancel an ongoing request

Another detail that's easy to overlook is the difference between stopping a timer and stopping its work.

Consider this implementation:

const timer = setInterval(async () => {
  const response = await fetch("/api/status");
  const data = await response.json();

  updateDashboard(data);
}, 5000);

When the user navigates away from the dashboard, we call:

clearInterval(timer);

That prevents future timer callbacks from starting.

But what happens to a request that's already running?

It can continue until it completes.

This matters particularly in single-page applications, where components can be mounted and unmounted while asynchronous operations are still outstanding.

We can solve this using AbortController.

The Fetch and DOM standards provide a cancellation mechanism through abort signals, allowing us to interrupt supported asynchronous operations. 

fetch.spec.whatwg.org+1

Building a reusable polling utility

Instead of implementing timer management separately in every part of our application, let's create a small utility.

function startPolling(
  task,
  {
    interval = 5000,
    timeout = 10000,
    onError = console.error
  } = {}
) {
  let stopped = false;
  let timer;

  const controller = new AbortController();

  async function run() {
    if (stopped) return;

    try {
      const signal = AbortSignal.any([
        controller.signal,
        AbortSignal.timeout(timeout)
      ]);

      await task(signal);
    } catch (error) {
      if (!stopped) {
        onError(error);
      }
    } finally {
      if (!stopped) {
        timer = setTimeout(run, interval);
      }
    }
  }

  run();

  return function stop() {
    stopped = true;

    clearTimeout(timer);
    controller.abort();
  };
}

The utility provides several useful behaviours:

  • Executes the first operation immediately.

  • Prevents overlapping executions within the same polling instance.

  • Supports request timeouts.

  • Handles asynchronous failures.

  • Cancels pending timers and signals active operations to stop.

Let's use it in a dashboard.

const stopPolling = startPolling(
  async signal => {
    const response = await fetch("/api/status", {
      signal
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const data = await response.json();

    signal.throwIfAborted();

    updateDashboard(data);
  },
  {
    interval: 5000,
    timeout: 10000
  }
);

Whenever we no longer need the updates:

stopPolling();

Notice that we're combining two different cancellation conditions using AbortSignal.any().

One signal handles manual cancellation. The other imposes a timeout on each operation. 

This requires a modern JavaScript runtime that supports these APIs.

It's also important to understand that cancellation is cooperative. The supplied task must respect the abort signal. If the task ignores it, the utility cannot forcibly terminate that operation.

Similarly, cancelling a network request doesn't guarantee that the server has stopped processing it.

7. Using the polling utility in React

If you're building React applications, this pattern becomes particularly useful.

One common mistake is starting a timer inside a component without properly cleaning it up.

useEffect(() => {
  setInterval(() => {
    fetchStatus();
  }, 5000);
}, []);

When the component unmounts, the timer can continue running.

If the component is mounted again, another timer may be created.

Over time, you could end up with several timers performing exactly the same work.

Using our polling utility, we can manage the entire lifecycle through useEffect().

import { useEffect, useState } from "react";
import { startPolling } from "./polling";

function Dashboard() {
  const [status, setStatus] = useState(null);

  useEffect(() => {
    const stop = startPolling(
      async signal => {
        const response = await fetch("/api/status", {
          signal
        });

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}`);
        }

        const data = await response.json();

        signal.throwIfAborted();

        setStatus(data);
      },
      {
        interval: 5000,
        timeout: 10000
      }
    );

    return stop;
  }, []);

  return (
    <div>
      <h2>System Status</h2>

      <pre>
        {JSON.stringify(status, null, 2)}
      </pre>
    </div>
  );
}

Assuming we've exported startPolling from our polling utility module, that's all we need.

When the component mounts, polling begins. When the component unmounts, React invokes the cleanup function, which stops the timer and aborts an outstanding fetch.

React's official documentation emphasises this setup-and-cleanup relationship for effects that interact with external systems. 

This is also important when using React Strict Mode, which performs an additional development-only setup and cleanup cycle to help identify lifecycle bugs.

For larger applications, libraries that already manage server state, polling, caching, retries and request deduplication may be preferable to maintaining your own polling implementation.

8. A JavaScript timer isn't an accurate clock

There's another common misuse of setInterval() that has nothing to do with API requests.

Consider a simple countdown timer.

let remaining = 60;

const timer = setInterval(() => {
  remaining--;

  console.log(remaining);

  if (remaining <= 0) {
    clearInterval(timer);
  }
}, 1000);

We assume that every callback represents exactly one elapsed second.

In reality, timer callbacks may be delayed.

The browser could be busy processing other JavaScript, the tab could be running in the background, or the operating system could suspend the application.

Node.js also explicitly makes no guarantee that timer callbacks will execute at precisely their requested times. 

Node.js v26.14.0 Documentation

Rather than counting how many times the callback executes, calculate how much time remains.

const deadline = Date.now() + 60000;

function updateCountdown() {
  const remaining = Math.max(
    0,
    Math.ceil((deadline - Date.now()) / 1000)
  );

  console.log(remaining);

  return remaining;
}

const timer = setInterval(() => {
  if (updateCountdown() === 0) {
    clearInterval(timer);
  }
}, 1000);

updateCountdown();

Now, if the browser delays an execution by several seconds, the next callback recalculates the remaining time rather than simply subtracting one.

For measuring elapsed time independently of system clock adjustments, performance.now() is generally more appropriate. For a countdown to an actual wall-clock deadline, Date.now() is useful.

Use timers to schedule updates. Use clocks to measure time.

That distinction can save you from some surprisingly difficult bugs.

9. Do we really need to poll all the time?

Imagine a user opens your dashboard, switches to another browser tab, and leaves it running for the rest of the working day.

Does your application still need to retrieve fresh information every five seconds?

At that interval, eight hours of uninterrupted polling could theoretically initiate 5,760 requests from a single browser tab. Actual numbers may be lower because browsers can throttle timers in background tabs.

For many dashboards, those requests provide little benefit while the page isn't visible.

The Page Visibility API gives us a way to detect when a document becomes hidden or visible. 

html.spec.whatwg.org+1

We can combine it with our polling utility.

let stopPolling;

function syncPolling() {
  if (document.hidden) {
    stopPolling?.();
    stopPolling = undefined;

    return;
  }

  if (!stopPolling) {
    stopPolling = startPolling(
      async signal => {
        const response = await fetch("/api/status", {
          signal
        });

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}`);
        }

        const data = await response.json();

        signal.throwIfAborted();

        updateDashboard(data);
      }
    );
  }
}

document.addEventListener(
  "visibilitychange",
  syncPolling
);

syncPolling();

When the document becomes hidden, polling stops.

When the user returns, polling resumes with an immediate update.

If this code belongs to a component or dynamically loaded module, we should also provide cleanup.

function dispose() {
  document.removeEventListener(
    "visibilitychange",
    syncPolling
  );

  stopPolling?.();
  stopPolling = undefined;
}

Not every application should behave this way. Some applications legitimately need background updates.

But for ordinary dashboards and status displays, visibility-aware polling can be a useful optimisation.

Bonus: Slow down when things go wrong

So far, we've focused on preventing overlapping requests.

But consider what happens when a service becomes temporarily unavailable.

Our application might continue retrying every five seconds, even when the server is consistently returning errors.

Instead, we could gradually increase the delay between failed attempts using exponential backoff.

Exponential backoff retry delays. Retry delays increase from five to ten, twenty, forty, and sixty seconds, then remain capped at sixty seconds before jitter is applied.
Retry delays increase from five to ten, twenty, forty, and sixty seconds, then remain capped at sixty seconds before jitter is applied.
SVG source
<svg xmlns="http://www.w3.org/2000/svg"
     id="bw-retry-backoff"
     viewBox="0 0 760 360"
     width="760" height="360"
     role="img" aria-labelledby="bw-retry-backoff-title"
     aria-describedby="bw-retry-backoff-desc">

  <title id="bw-retry-backoff-title">
    Exponential backoff retry delays
  </title>
  <desc id="bw-retry-backoff-desc">Retry delays increase from five to ten, twenty, forty, and sixty seconds, then remain capped at sixty seconds before jitter is applied.</desc>

  <style>
    #bw-retry-backoff [fill="#111111"] { fill: #ffffff; }
    #bw-retry-backoff [fill="#eeeeee"] { fill: #0f172a; }
    #bw-retry-backoff [fill="#aaaaaa"] { fill: #64748b; }
    #bw-retry-backoff [fill="#292929"] { fill: #f1f5f9; }
    #bw-retry-backoff [fill="#d97706"] { fill: #b45309; }
  </style>

  <rect width="760" height="360" rx="12" fill="#111111"/>

  <g font-family="Arial, Helvetica, sans-serif">

    <text x="24" y="35" font-size="20"
          font-weight="600" fill="#eeeeee">
      Exponential backoff
    </text>

    <text x="24" y="58" font-size="13" fill="#aaaaaa">
      Base delay: 5 seconds | Maximum delay: 60 seconds
    </text>

    <!-- Labels -->
    <g fill="#eeeeee" font-size="14">
      <text x="24" y="101">Failure 1</text>
      <text x="24" y="141">Failure 2</text>
      <text x="24" y="181">Failure 3</text>
      <text x="24" y="221">Failure 4</text>
      <text x="24" y="261">Failure 5</text>
      <text x="24" y="301">Failure 6</text>
    </g>

    <!-- Background tracks -->
    <g fill="#292929">
      <rect x="120" y="85" width="540" height="24" rx="5"/>
      <rect x="120" y="125" width="540" height="24" rx="5"/>
      <rect x="120" y="165" width="540" height="24" rx="5"/>
      <rect x="120" y="205" width="540" height="24" rx="5"/>
      <rect x="120" y="245" width="540" height="24" rx="5"/>
      <rect x="120" y="285" width="540" height="24" rx="5"/>
    </g>

    <!-- Retry delay bars -->
    <g fill="#d97706">
      <rect x="120" y="85" width="45" height="24" rx="5"/>
      <rect x="120" y="125" width="90" height="24" rx="5"/>
      <rect x="120" y="165" width="180" height="24" rx="5"/>
      <rect x="120" y="205" width="360" height="24" rx="5"/>
      <rect x="120" y="245" width="540" height="24" rx="5"/>
      <rect x="120" y="285" width="540" height="24" rx="5"/>
    </g>

    <!-- Duration labels -->
    <g fill="#eeeeee" font-size="14" text-anchor="end">
      <text x="730" y="102">5s</text>
      <text x="730" y="142">10s</text>
      <text x="730" y="182">20s</text>
      <text x="730" y="222">40s</text>
      <text x="730" y="262">60s</text>
      <text x="730" y="302">60s</text>
    </g>

    <text x="24" y="340" font-size="12" fill="#aaaaaa">
      Delays shown before applying random jitter. Reset after success.
    </text>

  </g>
</svg>
Download SVG

Example retry delays with a five-second base and a sixty-second maximum, before adding random jitter.

Here's a small function for calculating those delays.

function getRetryDelay(failures) {
  const base = 5000;
  const maximum = 60000;

  const delay = Math.min(
    base * 2 ** Math.max(0, failures - 1),
    maximum
  );

  // Random jitter between 50% and 100%
  return Math.round(
    delay * (0.5 + Math.random() * 0.5)
  );
}

The random variation, known as jitter, helps prevent large numbers of clients from retrying at exactly the same time.

After a successful request, we can reset the failure counter and return to our normal polling interval.

A production implementation should also distinguish between transient failures and permanent errors, respect applicable Retry-After responses, and avoid blindly retrying operations that have side effects.

Retry strategies deserve an article of their own, but they're worth considering whenever you're implementing a recurring network operation.

Which scheduling approach should you use?

RequirementRecommended approach
Simple periodic UI updatesetInterval()
Update a countdownTimer with a calculated deadline
Poll an API without overlapping requestsRecursive setTimeout()
Maintain periodic ticks but skip busy periodssetInterval() with an execution guard
Cancel ongoing network operationsAbortController
Limit request durationAbortSignal.timeout()
Retry temporarily unavailable servicesExponential backoff with jitter
Receive server-driven updatesServer-Sent Events or WebSockets
Smooth browser animationsrequestAnimationFrame()
Persistent backend jobsJob queue or dedicated scheduler

There isn't a single scheduling technique that works best for every situation.

The correct approach depends on what should happen when an operation takes longer than expected, fails, or is no longer needed.

Final thoughts

setInterval() isn't a bad JavaScript API.

It's a perfectly reasonable choice when we need to execute a small, periodic operation.

The problem begins when we use it as though it understands the asynchronous work happening inside its callback.

It doesn't know that your API request is still running.

It doesn't know that an older response could overwrite newer data.

It doesn't know that your database is overloaded, or that the user has already left the page.

Those decisions belong to our application.

The next time you're about to write a setInterval() with an asynchronous callback, ask yourself one question:

What should happen if the previous execution hasn't finished yet?

The answer might change how you write the entire function.

THE CONVERSATION

Comments

Add your perspective ↓

Questions, useful examples and different approaches are welcome. Keep the discussion thoughtful and on topic.

Loading comments…

    Add your perspective

    All comments are reviewed before publication. Your name and comment will be public after approval; your email stays private and is used for account access or moderation, not a mailing list.

    Checking sign-in…