Timers & requestAnimationFrame
Master browser timing functions. Learn the difference between classic timeouts, intervals, and the high-performance requestAnimationFrame API.
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
setInterval(animate, 16);
// Blindly pushes to the Macrotask Queue
// Doesn't care if a frame is dropped
function loop() {
animate();
requestAnimationFrame(loop);
}
// Perfectly synced with the screen repaint
// Automatically pauses in background tabs
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
setTimeoutandsetIntervalhand tasks to the Web APIs.- The delay is a minimum guarantee, not an exact execution time.
requestAnimationFrameschedules 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.