Timers & requestAnimationFrame

Master browser timing functions. Learn the difference between classic timeouts, intervals, and the high-performance requestAnimationFrame API.

JavaScript6 min readConcept 37 of 62

Scheduling Code

JavaScript cannot magically pause itself because it only has one thread. If you want code to run in the future, you must hand it over to the browser's Web APIs.

The browser will hold onto your function and push it back into the Event Loop when the time is right.

The Minimum Guarantee

setTimeout(fn, 1000) schedules a function to run after 1000 milliseconds.

However, it is critical to understand that this is a **minimum guarantee**, not an exact appointment. If your main thread is busy doing heavy calculations, your timer callback will be stuck waiting in the Macrotask Queue until the stack is completely empty.

The Animation Standard

requestAnimationFrame(fn) (often abbreviated as rAF) is specifically designed for animations.

Instead of guessing how many milliseconds to wait, rAF asks the browser to run your function right before the next screen repaint (usually 60 times a second). This results in buttery smooth, jank-free animations.

The Scheduling Flow

Examine this architectural breakdown comparing the classic timer approach against the modern animation approach.

Scheduling Architecture

// 1. The Classic Timer
setInterval(animate, 16);
// Blindly pushes to the Macrotask Queue
// Doesn't care if a frame is dropped
// 2. The Modern Animation Loop
function loop() {
animate();
requestAnimationFrame(loop);
}
// Perfectly synced with the screen repaint
// Automatically pauses in background tabs
setInterval
The Macrotask Trap
0ms
16ms
32ms (Dropped)
48ms
JS Work
Heavy Code (Blocked)
Fires Late!
requestAnimationFrame
The Paint PipelineActive Tab
Frame 1
JS
Style
Paint Screen
Frame 2
JS
Style
Paint Screen
Background TabBattery Saved
Frame X
rAF Loop Paused by Browser
iBecause requestAnimationFrame syncs perfectly with the browser's Paint Pipeline, it creates buttery-smooth animations that never drop frames, while automatically pausing in background tabs!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1If you call `setTimeout(myFunction, 0)`, when does `myFunction` run?
  2. 2Why is `requestAnimationFrame` better than `setInterval` for animations?
  3. 3What happens if you run a very slow `while` loop that takes 3 seconds, and you have a `setTimeout` set for 1 second?

Remember this

  • setTimeout and setInterval hand tasks to the Web APIs.
  • The delay is a minimum guarantee, not an exact execution time.
  • requestAnimationFrame schedules code right before the next screen repaint.
  • rAF is battery-efficient because it pauses when the tab is hidden.
  • Always clear your timers using the returned ID to prevent memory leaks.

Done with this concept?

Mark it complete to track your progress. No login needed.