oddworks blog

requestAnimationFrame in background tabs: why it stops and fixes

On this page
  1. Why rAF stops
  2. See the gap yourself
  3. Handling the jump on return
  4. Work that has to keep running
  5. requestVideoFrameCallback stops too
  6. If you're a user, not the developer
  7. FAQ

Browsers stop calling requestAnimationFrame() callbacks while a tab is in the background, a window is minimized, or an iframe is hidden. Nothing is lost: a pending callback stays queued and runs once when the tab is visible again, with a timestamp that has jumped forward by however long you were away. Code that assumes "one callback every 16 ms" breaks on that jump, and code that does real work inside rAF simply stops.

Why rAF stops

rAF exists to run code right before the browser paints a frame. A hidden tab paints nothing, so there is nothing to sync to. MDN puts it directly: rAF calls "are paused in most browsers when running in background tabs or hidden <iframe>s, in order to improve performance and battery life."

Chrome's own guidance says the same thing from the other side. In its post on timer throttling, the Chrome team recommends rAF for animation precisely because it "will wait for the page to be visible, so it doesn't use any CPU when the page is hidden."

Some details worth knowing:

  • Paused, not slowed. Timers in a hidden tab are throttled to run less often. rAF callbacks don't run at all until the page is visible.
  • Focus doesn't matter. A visible window that has lost focus (you clicked another app beside it) keeps getting frames. Only visibility counts. The Page Visibility API guide explains the difference.
  • Audio doesn't help. A tab playing sound gets lighter timer throttling, but it still isn't painting, so rAF stays paused.

See the gap yourself

Paste this into the console, switch tabs for ten seconds, and come back:

let last = performance.now();

function frame(now) {
  const gap = now - last;
  if (gap > 1000) {
    console.log(`No frames for ${Math.round(gap)} ms`);
  }
  last = now;
  requestAnimationFrame(frame);
}

requestAnimationFrame(frame);

You'll see one line with a gap close to the time you were away. This is also how a page can tell you left without any events: it measures the hole in its frame timeline. Our live test shows this check alongside the visibility and focus signals.

Handling the jump on return

The first callback after a long absence gets a large now - last. If you feed that straight into physics or an animation, objects teleport, fall through floors, or a "catch-up" loop freezes the tab while it simulates minutes of game time.

Clamp the frame time

A fixed-step loop with a cap on how much time one frame may simulate handles this cleanly:

const STEP = 1000 / 60;   // simulation step in ms
const MAX_FRAME = 250;    // never simulate more than this per frame

let last = null;
let acc = 0;

function loop(now) {
  if (last === null) last = now;
  const frameTime = Math.min(now - last, MAX_FRAME);
  last = now;

  acc += frameTime;
  while (acc >= STEP) {
    update(STEP);         // your game or simulation step
    acc -= STEP;
  }
  render(acc / STEP);     // your drawing code, with interpolation alpha

  requestAnimationFrame(loop);
}

requestAnimationFrame(loop);

// Drop the time spent hidden instead of simulating it.
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible') last = null;
});

update and render are your functions. The cap alone already protects you. Resetting last on return makes the restart clean, so the game resumes where it paused.

Derive state from the clock, not from frame counts

For countdowns, progress bars and anything tied to real time, store the target time and compute the display from it each frame. When rAF resumes, the first frame shows the right value.

const label = document.querySelector('#timer');
const endsAt = performance.now() + 5 * 60 * 1000; // five minutes from now

function tick() {
  const left = Math.max(0, endsAt - performance.now());
  label.textContent = `${Math.ceil(left / 1000)} s`;
  if (left > 0) requestAnimationFrame(tick);
}

requestAnimationFrame(tick);

performance.now() keeps advancing while the tab is hidden, so left is correct the moment you look again. A version that subtracts 16 ms per frame would be minutes behind.

Work that has to keep running

If something must happen while the tab is hidden (a sync, a timer that plays a sound, a game server tick), rAF is the wrong tool. Move it somewhere that still runs.

Main-thread timers, with limits

setTimeout and setInterval keep running in hidden tabs, but throttled. Per Chrome's post, a hidden tab's timers are checked about once a second. After the page has been hidden for more than five minutes, silent for 30 seconds, with a chain of five or more timers and no WebRTC in use, Chrome checks them only once a minute. Background tab throttling covers the stages and which flags still matter.

So a 1-second interval is fine for a while, then becomes a 1-minute interval. Write timer code that measures elapsed time (as above) instead of counting ticks.

A dedicated worker clock

Chrome's intensive throttling rules are written for timers on a window. Timers inside a dedicated Web Worker are a common workaround because they aren't covered by those rules. Behaviour can differ between browsers, so test it where you ship.

const workerSource = `
  let id = null;
  onmessage = (event) => {
    if (event.data === 'start' && id === null) {
      id = setInterval(() => postMessage('tick'), 1000);
    } else if (event.data === 'stop') {
      clearInterval(id);
      id = null;
    }
  };
`;

const blob = new Blob([workerSource], { type: 'text/javascript' });
const worker = new Worker(URL.createObjectURL(blob));

worker.onmessage = () => {
  // Runs on the main thread when the worker's tick arrives.
  console.log('tick', document.visibilityState);
};

worker.postMessage('start');

The worker posts a message, and your handler on the main thread does the work. If your site's Content Security Policy blocks blob: workers, put the worker code in its own file and load it with new Worker('/clock-worker.js').

Push instead of poll

If you're using rAF or a timer to check whether something changed, a push channel is better. MDN notes that pages with an open WebSocket or WebRTC connection aren't throttled the same way, so the connection stays up and events arrive while the tab is hidden.

requestVideoFrameCallback stops too

video.requestVideoFrameCallback() is the per-frame callback for video. It fires when a frame is presented to the compositor, and a hidden tab stops presenting frames, so these callbacks stall the same way. If you process video frames (captions, overlays, analysis), handle the gap the same way: clamp, or derive state from video.currentTime.

If you're a user, not the developer

If a page you're using freezes its animation, game or player every time you switch tabs because it depends on rAF, you can't change its code. You can make the browser keep calling it.

Focus Spoofer (which we make) is a free extension for Chrome, Edge and Brave that keeps requestAnimationFrame and requestVideoFrameCallback firing in hidden tabs, on the tabs you turn it on for or on sites you mark "Always protect". The callbacks run on a fallback clock while the tab is hidden; nothing is painted until you come back, but the page's logic keeps going. It also keeps document.hidden false and blocks visibilitychange, so pages that check visibility directly don't pause either. How to disable the Page Visibility API compares it with a userscript and uBlock Origin filters.

It has limits. It doesn't stop Memory Saver or sleeping tabs from discarding a tab, it doesn't work on mobile, Firefox or Safari, and it can't run on chrome:// pages, the Chrome Web Store or the PDF viewer. Get it from the product page.

FAQ

Does requestAnimationFrame run in background tabs?

No. Browsers pause rAF callbacks while the tab is hidden, the window is minimized, or the iframe is hidden. A pending callback runs once when the page is visible again.

Why does my animation jump when I come back to the tab?

The first callback after returning receives a timestamp that includes all the time you were away. Clamp the frame delta, or reset your last-frame time in a visibilitychange handler.

Is rAF throttled when the window loses focus but is still visible?

No. Visibility controls rAF, not focus. A window that's on screen but not focused keeps receiving frames.

What should I use instead of rAF for background work?

Use timers that measure elapsed time, a dedicated worker for a steadier clock, or a WebSocket or server-sent events for updates. Keep rAF for drawing.

Can I make rAF keep firing in a hidden tab?

Not from page code. A browser extension such as Focus Spoofer can keep the callbacks running on the tabs you choose, but nothing is drawn until the tab is visible.

Keep reading

Start with the overview: Page Visibility API explained: document.hidden vs visibilityState