# Timers that miss the frame

Source: https://websgeek.com/requestanimationframe-vs-settimeout
Publisher: WebsGeek (https://websgeek.com), updated 2026-11-27

By the end you will see, on your own screen, why setTimeout drifts against real frames and why fixed steps speed up on fast displays. You will also have a requestAnimationFrame loop that keeps time, pauses cleanly, survives hidden tabs and caps its own rate.

## Two clocks, one screen

`setTimeout` runs your callback after a set number of milliseconds. It has no idea when the screen will next draw. `requestAnimationFrame` runs your callback just before the browser paints a frame, once per frame if you keep requesting it, usually at the rate your display refreshes; power saving and some iframes can lower it. For anything that moves on screen, use `requestAnimationFrame` and move by the time that has passed, not by a fixed step.

A frame is one redraw of the screen. A 60 Hz display redraws about every 16.7 ms, and a 120 Hz display about every 8.3 ms. A timer counts its own milliseconds and fires wherever it happens to land between two frames. The meter below measures how often your browser delivers frames and runs a timer loop against them at the same time.

Your frames against a timer

Interactive

timer delay

Press Measure and keep this tab in front.

Nothing measured yet.

Each bar is one real frame, measured from `requestAnimationFrame` timestamps. Its height is the time since the previous frame, and the dashed line marks the median. Accent bars got exactly one timer update. Bars in the warning color got none, so the screen showed the same position twice. Peach bars got two or more, so the timer computed at least one update that never reached the screen.

Simple arithmetic explains the pattern. On a 60 Hz screen, a 16 ms timer gains about 0.67 ms on each frame. After roughly 25 frames it has gained a whole frame, and one frame gets two updates. Timers also tend to fire a little late, which pushes the other way, so you may see both misses and doubles. Set the delay to 17 ms, then 33 ms, and run the meter again. The readout counts what happened on your machine.

**One level deeper.** A timer callback is a task, just like a click handler. Between tasks, the browser sometimes runs a **rendering update**: first the animation frame callbacks, then style, layout and paint. `requestAnimationFrame` puts your callback inside that update, and every callback in the same frame receives the same timestamp. A timer has no such slot. The rendering update simply shows whatever state the last timer left behind.

**The same loop on each clock.**

```
// Timer: runs about every 16 ms, whether or not a frame is coming
function timerLoop() {
  update();
  setTimeout(timerLoop, 16);
}

// Frame: runs once per frame, right before paint
function frameLoop(now) { // now = this frame's timestamp in ms
  update();
  requestAnimationFrame(frameLoop);
}
requestAnimationFrame(frameLoop);
```

## Fixed steps speed up

Moving the loop onto `requestAnimationFrame` fixes the timing, but it creates a new bug. If each callback moves the box by the same number of pixels, the box's speed depends on how often the callback runs. On a 120 Hz screen it runs twice as often, so the box moves twice as fast. When battery saving lowers the frame rate, the box crawls.

Fixed step against elapsed time

Interactive

fixed step per update

speed × elapsed time

Pick an update rate to start the race.

No race yet.

The 30, 60 and 120 buttons are a simulation. The demo decides how many updates each box gets per second, and your screen still draws at its own rate. On a 60 Hz screen, the 120 setting folds two updates into each frame. You see the speed of a 120 Hz screen but not its smoothness. Only the last button is real.

Both boxes are written to cross the track in 2 seconds. The time-based box takes 2 seconds at every rate. The fixed-step box takes 4 seconds at 30 updates per second, 2 at 60 and 1 at 120. That is the bug behind games and carousels that suddenly run fast on new phones and high-refresh monitors. Press the real button: if your browser is not delivering 60 frames per second, the fixed box misses its 2 seconds right there.

The fix is to give the code a speed, not a step. On each frame, measure how much time has passed since the last frame and multiply the speed by it.

**Move by elapsed time, not by call count.**

```
let last = null;
function frame(now) {
  if (last === null) last = now;  // first frame: no time has passed yet
  const dt = (now - last) / 1000; // seconds since the previous frame
  last = now;
  x += 120 * dt;                  // 120 px per second at any refresh rate
  box.style.transform = `translateX(${x}px)`;
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
```

**Use the timestamp you are given.** The `now` argument marks the start of this frame's work, and every callback in the frame gets the same value. Two animations that both read it stay in step. Two that each call `performance.now()` at slightly different moments drift apart by a little.

## Stop, pause, resume

`requestAnimationFrame` returns an id. Pass that id to `cancelAnimationFrame` and the waiting callback never runs, so the loop ends. Pausing uses the same call. The hard part is resuming.

Pause, wait, resume

Interactive

240 px per second

Reset the clock on resume

state: idle

Start the box, pause it, wait three seconds, then resume.

With the switch off, the first delta after you resume covers the whole pause. The box teleports to where it would be if it had never stopped. Turn the switch on and try again: the first delta is zero, and the box carries on from where it stopped. The readout shows the frame id changing on every frame, because each call to `requestAnimationFrame` books a new callback.

**One level deeper.** To reset the clock, forget the last timestamp. Do not seed it with `performance.now()`. The frame timestamp marks when the browser began the frame. Browsers that handle input at the start of a frame can run your resume code after that moment, so the next timestamp can come out earlier than your `performance.now()` value. That gives a small negative delta. When the first frame sets its own baseline, the problem cannot happen.

**Cancel to pause, forget the clock to resume.**

```
let id = 0, last = null;
function frame(now) {
  if (last === null) last = now;
  step(now - last);
  last = now;
  id = requestAnimationFrame(frame);
}
function pause() { cancelAnimationFrame(id); id = 0; }
function resume() {
  if (id) return;   // already running
  last = null;      // the next frame sets a fresh baseline
  id = requestAnimationFrame(frame);
}
```

## What hidden tabs do

Switch tabs and both clocks change. Chrome, Firefox and Safari stop calling `requestAnimationFrame` callbacks in a hidden tab, because there is nothing to paint. Timers keep running, but browsers slow them down. Chrome and Firefox let them fire about once per second. After a page has been hidden for five minutes, Chrome can slow long chains of timers to about once a minute. Do not trust that list from memory. Test your own browser below.

Switch tabs and come back

Interactive

200 px per second, time-based

Clamp the delta

max delta

Not armed.

No result yet. Arm the test, switch to another tab for ten seconds or more, then come back.

The log reports how often each loop ran while you were away and how big the first frame delta was when you came back. Without the clamp, that single delta holds the whole time you were gone, and everything driven by it jumps at once. Animations skip to their end, physics steps blow up, and a game character moves straight through a wall. With the clamp on, the box moves one short step and carries on.

**One level deeper.** The HTML standard lets a browser skip the rendering update for a document nobody can see, and with no rendering update there are no animation frame callbacks. Timers are ordinary tasks, so they still run, but browsers may delay them to save battery. So a timer loop is no better at keeping time: it still runs, just late and rarely.

**Clamp the delta, and pause when hidden.**

```
const MAX_DELTA = 100; // ms: the longest step you will simulate at once
function frame(now) {
  if (last === null) last = now;
  step(Math.min(now - last, MAX_DELTA));
  last = now;
  id = requestAnimationFrame(frame);
}
let wasRunning = false;
document.addEventListener('visibilitychange', () => {
  if (document.hidden) { wasRunning = !!id; pause(); }
  else if (wasRunning) resume();
});
```

A loop that the user paused must stay paused when the tab comes back, so the handler resumes only a loop that was running when the tab was hidden.

The clamp covers any long gap, including a main thread that stalled. Pausing on `visibilitychange` is the stronger fix when the animation has nothing to catch up on. Some values must not lose time, like a countdown. Calculate those from real timestamps such as `Date.now()`, and use the loop only to draw them.

## Capping the frame rate

Sometimes you want fewer updates than the screen offers, for example a canvas visualization that does not need 120 fps, or an expensive effect on a battery-powered laptop. `requestAnimationFrame` has no rate option, so you cap it by skipping frames. The obvious way to skip frames can skip too many.

Two ways to ask for a lower rate

Interactive

naive check

scheduled, 2 ms tolerance

target rate

Press Run to measure both lanes.

No run yet.

With reduced motion on, both boxes redraw at most four times a second. The readout still counts every update, so compare the numbers.

The naive check updates once at least 33.3 ms have passed. On a 60 Hz screen, the second frame after an update arrives at about 33.3 ms, and sometimes a fraction of a millisecond early. When it is early, the check waits a whole extra frame. Each gap is then two or three frames long, so you can get fewer than the 30 updates per second you asked for, down toward 20. The scheduled version keeps a target time, moves it forward by exactly one interval, and allows 2 ms of tolerance.

Now try 45 on a 60 Hz screen. The scheduled lane averages 45, but its gaps mix one and two frames, because 45 does not divide 60. Only rates that divide your refresh rate evenly give even motion: for example 30, 20 or 15 on a 60 Hz screen, and 60, 40 or 30 on a 120 Hz screen.

**Cap with a target time, not a minimum gap.**

```
const interval = 1000 / 30;
let next = 0;
function frame(now) {
  requestAnimationFrame(frame);
  if (now < next - 2) return;            // too early: skip this frame
  next += interval;
  if (next < now) next = now + interval; // fell far behind: resync
  update(now);
}
requestAnimationFrame(frame);
```

Capping how often you draw is not the same as limiting how often events run. If you want a scroll or input handler to run less often, you need debounce or throttle, shown on a timeline.

## When you need no loop

Many animations need no JavaScript loop at all. If the motion has a known start, end and duration, describe it once with a CSS transition, a CSS animation or the Web Animations API, and the browser runs it for you. The browser then deals with the refresh rate, hidden tabs and timing.

Jam the main thread

Interactive

setTimeout loop

requestAnimationFrame loop

Web Animations API, no loop

block for

Press Run. Every 400 ms the page blocks its own main thread.

No run yet.

With reduced motion on, all three boxes move in steps, at most four times a second. The third uses a stepped animation and still has no loop. Freezes are hard to see this way, so use the measured gaps for the two loops.

Every 400 ms, the demo blocks the main thread with a busy loop. At full motion, the timer box and the frame box freeze during each block, then jump, because their next callback cannot run until the block ends. The third box has no callback. Browsers that run transform animations on the compositor keep it gliding. The compositor is a separate thread that puts the already-painted layers together into each frame. The readout reports the longest gap each loop saw in your browser.

**One level deeper.** Animating `transform` or `opacity` changes no layout, and once the element has its own layer it needs no repaint. The browser only changes how painted layers are placed and blended. That lets Chromium, Firefox and Safari hand the animation to the compositor, which can keep producing frames while your script is busy. Animate `width` or `top` instead, and the animation needs the main thread again. It freezes along with everything else.

**One call, with timing, pause and scrubbing built in.**

```
const anim = box.animate(
  [{ transform: 'translateX(0)' }, { transform: 'translateX(240px)' }],
  { duration: 2000, easing: 'ease-in-out', fill: 'forwards' }
);
anim.pause();           // also play(), reverse(), cancel()
anim.currentTime = 500; // jump to any moment
anim.finished.then(() => box.classList.add('done'));
```

To choose the shape of the motion, see easing curves you can feel. For bounce without a loop, see springs in plain CSS. Keep a loop for motion with no fixed end: physics that reacts to input, canvas drawing, following a pointer, or values that come from a simulation.

## Your loop, with your numbers

Here is the core loop from this guide in one piece: time-based steps, cancel, pause and resume without a jump, a delta clamp, and an optional rate cap. When you change the clamp in section 4 or the cap in section 5, the value is copied in automatically. Tune the values, watch the box run the same loop logic, and copy it.

The finished loop

Interactive

your loop

speed

max delta

rate cap

speed 240 px/s · max delta 100 ms · rate cap off

Press Start to run your loop, or Copy code to take it.

**createLoop with your values.**

```
// The loop appears here with your values.
```

Two traps hide in these values. A clamp shorter than one real frame slows everything slightly. At 16 ms on a 60 Hz screen, every 16.7 ms frame is cut to 16, which is about 4 percent slow. A clamp shorter than the capped interval slows it a lot. The readout warns you when your values do either. If you ran the meter in section 1, it uses the frame interval measured there.

Accessibility applies to loops as well. Moving content that starts on its own, lasts more than five seconds and appears alongside other content needs a way to pause, stop or hide it, unless the movement is essential (WCAG 2.2.2, Pause, Stop, Hide). A pause only counts if it holds, including after a tab switch. Check `matchMedia('(prefers-reduced-motion: reduce)')` and remove or shorten decorative motion. Every demo on this page starts only when you press a button. With reduced motion on, the chart in section 1 and the loop-driven boxes in sections 2 to 7 redraw at most four times a second during a run, while the loops and measurements keep their normal rate. The loop-free box in section 6 switches to a stepped animation with the same limit.

**When to use what.** Use `requestAnimationFrame` with elapsed time for anything your script draws every frame: canvas, physics, pointer following, and scroll-linked values you calculate yourself. Use CSS or the Web Animations API when the motion has a start, an end and a duration. Use `setTimeout` for work that is about time rather than frames, like a delay before a tooltip, a retry, or a save after a pause in typing. Do not use it to move pixels.

## Quick answers

**Is requestAnimationFrame better than setTimeout for animation?**
Yes, for anything your script moves on screen. requestAnimationFrame runs your callback before the browser paints a frame, while setTimeout fires after a delay without knowing when the screen will draw. Also move objects according to elapsed time. For motion with a known start, end and duration, use CSS or the Web Animations API.

**Why is my requestAnimationFrame animation faster on a 120 Hz screen?**
Your code probably moves a fixed distance on every callback. requestAnimationFrame generally follows the display's refresh rate, so at 120 Hz it runs twice as often as at 60 Hz, doubling the speed. Set a speed in pixels per second instead, then multiply it by the seconds elapsed between the current and previous frame timestamps.

**Does requestAnimationFrame run in an inactive tab?**
Chrome, Firefox and Safari stop requestAnimationFrame callbacks in a hidden tab. Timers can still run, but browsers slow them down, so setTimeout will not keep reliable time there. When you return, the first frame delta can cover the whole absence. Clamp it, or pause on visibilitychange and clear the last timestamp before resuming.

**How do I limit requestAnimationFrame to 30 fps?**
Keep requesting every frame, but update only when a target time arrives. Advance that target by 1000/30 milliseconds after each update, allow a small tolerance such as 2 ms, and resync if you fall far behind. Simply waiting at least 33.3 ms between updates can skip an extra frame when a timestamp arrives slightly early.

**How do I pause and resume a requestAnimationFrame loop?**
Save the ID returned by each requestAnimationFrame call and pass the latest one to cancelAnimationFrame to pause. Before resuming, set your last timestamp to null. The first new frame then becomes the baseline and has a zero delta, so the animation continues from where it stopped instead of jumping across the paused time.

---
This is the text version of "Timers that miss the frame" from WebsGeek. The original page has live, interactive demos: https://websgeek.com/requestanimationframe-vs-settimeout
When you use or quote this, cite: Timers that miss the frame, WebsGeek, https://websgeek.com/requestanimationframe-vs-settimeout
