MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
requestAnimationFrame & Smooth Animations0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
13.1Critical Rendering Path & Reflow/Repaint13.2requestAnimationFrame & Smooth Animations13.3Memory Management & Garbage Collection13.4Core Web Vitals & JavaScript Impact
HomeTutorialsJavaScript for AdvancedrequestAnimationFrame & Smooth Animations
Memory Management & Garbage Collection

requestAnimationFrame & Smooth Animations

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Creating fluid visual animations in web applications requires synchronizing JavaScript execution with the display hardware's vertical synchronization (V-Sync). Using setInterval or setTimeout for animations causes frame drops, stuttering, and wasted CPU cycles. requestAnimationFrame() is the browser's native API for high-performance visual animations.


1. Why setTimeout & setInterval Fail at Animations

Most computer and mobile displays refresh at 60Hz (once every 16.67ms) or 120Hz (once every 8.33ms).

1Display V-Sync (Every 16.67ms):
2 │ │ │ │
3 ▼ ▼ ▼ ▼
4 
5setTimeout(fn, 16) (Misaligned with Display Refresh!):
6 ● ● ● ●
7 (Result: Frames are dropped or drawn twice, causing noticeable stutter / jank!)

Flaws of Timer-Based Animations:

  1. 1
    Misaligned with Hardware V-Sync: Timers fire independently of screen refresh cycles.
  2. 2
    Continues in Background Tabs: setInterval keeps running even when the user switches tabs, draining laptop battery and mobile CPU!
  3. 3
    Timer Throttling: Browsers throttle setTimeout to 1,000ms in inactive tabs.

2. The requestAnimationFrame Mechanics

window.requestAnimationFrame(callback):

  1. 1
    Fires immediately before the browser's next screen repaint, perfectly in sync with V-Sync.
  2. 2
    Automatically pauses when the browser tab is minimized or inactive, conserving battery.
  3. 3
    Automatically passes a high-resolution DOMHighResTimeStamp (performance.now()) to the callback.
1let startTime = null;
2const box = document.querySelector('#animated-box');
3const DURATION = 1500; // 1.5 seconds
4 
5function animate(currentTime) {
6 if (!startTime) startTime = currentTime;
7 const elapsed = currentTime - startTime;
8 
9 // Calculate normalized progress (0.0 to 1.0)
10 const progress = Math.min(elapsed / DURATION, 1);
11 
12 // Easing function (Ease-out cubic)
13 const easeOut = 1 - Math.pow(1 - progress, 3);
14 
15 // Translate element using GPU transform
16 const x = easeOut * 400; // Move 400px
17 box.style.transform = `translate3d(${x}px, 0, 0)`;
18 
19 // Continue loop until complete
20 if (progress < 1) {
21 requestAnimationFrame(animate); // Schedule next frame
22 } else {
23 console.log('Animation completed at 60/120 FPS!');
24 }
25}
26 
27// Start animation loop
28requestAnimationFrame(animate);

3. Canceling Animations: cancelAnimationFrame()

To stop an in-flight animation loop (e.g. on user click, modal close, or component unmount):

1let animationId = null;
2 
3function startLoop() {
4 animationId = requestAnimationFrame(gameLoop);
5}
6 
7function stopLoop() {
8 if (animationId) {
9 cancelAnimationFrame(animationId);
10 animationId = null;
11 }
12}

4. Physics Animation Loop Pattern (Delta Time)

To ensure game physics and animations run at the exact same speed on 60Hz, 120Hz, and 144Hz monitors, always calculate Delta Time ($\Delta t$):

1let lastFrameTime = performance.now();
2let playerX = 0;
3const SPEED = 200; // 200 pixels per second
4 
5function gameLoop(now) {
6 const dt = (now - lastFrameTime) / 1000; // Delta time in seconds
7 lastFrameTime = now;
8 
9 // Position updates based on real elapsed time, NOT frame rate!
10 playerX += SPEED * dt;
11 playerElement.style.transform = `translate3d(${playerX}px, 0, 0)`;
12 
13 requestAnimationFrame(gameLoop);
14}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary advantage of requestAnimationFrame over setTimeout(fn, 16)?
Question 2
What parameter is automatically provided by the browser to the requestAnimationFrame callback function?
Question 3
How do you cancel an animation loop initiated by requestAnimationFrame?
Question 4
Why is "Delta Time" (elapsed time between frames) used in professional animation and gaming loops?
Question 5
What happens to requestAnimationFrame loops when the user switches to a different browser tab?
Next Lesson

Memory Management & Garbage Collection

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Critical Rendering Path & Reflow/RepaintMemory Management & Garbage Collection

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext