How do you create a smooth Canvas 2D loop with requestAnimationFrame?

Tests render pipeline timing. Outline: queue rAF per refresh; derive delta from timestamp for frame-rate independence; recurse each frame; cancel via cancelAnimationFrame. Red flag: claiming rAF locks 60fps, ignoring timestamp, or setInterval is fine.
WHAT IT TESTS: Browser render pipeline alignment and frame pacing. ANSWER OUTLINE: Schedule with requestAnimationFrame so the callback fires before the next repaint, matching the refresh rate, commonly 60 Hz but possibly 120 Hz or 144 Hz. Use the timestamp argument to compute delta time for frame-rate independent motion. Recursively queue requestAnimationFrame because each call is one-shot. Store the request ID and cancel with cancelAnimationFrame when stopping. RED FLAG: Claiming rAF locks 60fps, ignoring timestamp, or using setInterval works.
Read the original → developer.mozilla.org
- #requestanimationframe
- #canvas
- #animation
- #browser-apis
- #performance
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.