# Timers & requestAnimationFrame

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

Subject: JavaScript | Lesson 37 of 63 | 6 min read
Interactive lesson: https://codewithanimation.in/javascript/timers-and-raf
Previous: [Web Storage: localStorage, cookies & IndexedDB](https://codewithanimation.in/javascript/web-storage.md) | Next: [Observer APIs: Intersection, Mutation & Resize](https://codewithanimation.in/javascript/observer-apis.md)

## 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.

## Common mistake: The Background Tab Problem

If you use `setInterval` for an animation, it will blindly continue firing even if the user switches to a different tab, draining their battery and CPU.

By contrast, `requestAnimationFrame` is smart. If the tab becomes inactive, the browser automatically pauses rAF loops, saving massive amounts of system resources.

## Tip: Clearing Timers

Every scheduling function returns an ID. You must save this ID and pass it to `clearTimeout()`, `clearInterval()`, or `cancelAnimationFrame()` to stop the loop, otherwise you will create memory leaks!

## Try it: The Scheduling Flow

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

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/timers-and-raf

## Check yourself

### Question 1

If you call `setTimeout(myFunction, 0)`, when does `myFunction` run?

- A. As soon as the Call Stack is completely empty.
- B. Instantly, interrupting the current code.
- C. Before the next Promise resolves.

Correct answer: A

A timeout of 0 milliseconds simply pushes the callback to the end of the line (the Macrotask Queue), meaning it will run exactly when the main thread finishes its current work.

- Why not B: Incorrect. JavaScript is single-threaded; it never interrupts running code.
- Why not C: Incorrect. Promises (Microtasks) always run before setTimeouts (Macrotasks).

### Question 2

Why is `requestAnimationFrame` better than `setInterval` for animations?

- A. It syncs with the screen's refresh rate and pauses in background tabs.
- B. It runs on a separate CPU thread, making it infinitely faster.
- C. It automatically applies CSS transitions.

Correct answer: A

rAF provides smooth 60fps animations that perfectly match the hardware, while also being incredibly battery-efficient by pausing when hidden.

- Why not B: Incorrect. It still runs on the main thread.
- Why not C: Incorrect. It only schedules JavaScript execution.

### Question 3

What happens if you run a very slow `while` loop that takes 3 seconds, and you have a `setTimeout` set for 1 second?

- A. The setTimeout waits in the queue until the 3-second loop finishes.
- B. The setTimeout fires exactly at 1 second, pausing the while loop.
- C. The setTimeout is destroyed and never runs.

Correct answer: A

Timers only guarantee the *minimum* delay. A blocked Call Stack will delay all timers.

- Why not B: Incorrect. The single thread cannot be interrupted.
- Why not C: Incorrect. It will just be delayed.

## 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.
