#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
JavaScript Fundamentals

Animation

Animation with JavaScript means changing an element's style a little at a time, many times per second, so it appears to move, fade or grow. CSS transitions handle many simple effects, but JavaScript animation is useful when movement depends on user input, calculated positions or sequences that CSS cannot express easily, such as dragging, physics or a progress bar driven by data.

The old way: setInterval

Early scripts moved elements with a timer: every 10 or 20 milliseconds, add a pixel to the left position. It works, but the timer is not linked to the screen's refresh, so frames can be skipped or doubled and motion looks jerky. Timers also keep running in background tabs, wasting battery. You will still see this in older code, so it is worth recognising.

The better way: requestAnimationFrame

requestAnimationFrame(callback) asks the browser to call your function just before it paints the next frame. The browser passes a high-resolution timestamp, so you can base movement on elapsed time rather than on how many times the function ran. That keeps speed the same on slow and fast screens, and the browser pauses the loop in hidden tabs.

const box = document.querySelector('.box');
const distance = 300;      // pixels
const duration = 1000;     // milliseconds
let start = null;

function easeOutCubic(t) {
  return 1 - Math.pow(1 - t, 3);
}

function step(timestamp) {
  if (start === null) start = timestamp;
  const elapsed = timestamp - start;
  const progress = Math.min(elapsed / duration, 1);   // 0 to 1

  box.style.transform = `translateX(${easeOutCubic(progress) * distance}px)`;
  box.style.opacity = String(0.3 + 0.7 * progress);

  if (progress < 1) {
    requestAnimationFrame(step);
  }
}

document.querySelector('#play').addEventListener('click', () => {
  start = null;
  requestAnimationFrame(step);
});

The easing function bends the straight-line progress into a curve, so the box starts fast and slows down near the end. Changing easeOutCubic changes the feel without touching the rest of the code. To stop an animation early, save the id returned by requestAnimationFrame and pass it to cancelAnimationFrame.

The Web Animations API

Modern browsers also offer element.animate(), which takes CSS-like keyframes and timing options and runs them efficiently:

const anim = box.animate(
  [{ transform: 'scale(1)' }, { transform: 'scale(1.2)' }, { transform: 'scale(1)' }],
  { duration: 600, iterations: 2, easing: 'ease-in-out' }
);
anim.finished.then(() => console.log('Pulse complete'));

It returns an Animation object with pause(), play(), reverse() and a finished promise. For fixed keyframe effects controlled by script, it is often simpler than a manual loop.

Which properties to animate

Changing left, top, width or margin forces the browser to recalculate layout every frame, which can stutter on phones. transform and opacity can usually be handled without new layout work, so prefer them. Move with translate, grow with scale and fade with opacity.

A frequent bug: reading and writing in a loop

Reading a layout value such as offsetWidth right after writing a style forces the browser to calculate layout immediately. Doing this for many elements in one frame causes what developers call layout thrashing. Read all the values you need first, then write all the styles. Also store the start state in variables instead of reading it back from the DOM each frame.

Finally, respect users who have asked for less motion. Check window.matchMedia('(prefers-reduced-motion: reduce)').matches and skip or shorten large movements when it is true.

Picking the right tool

  • Simple hover or state change: a CSS transition.
  • Fixed keyframes controlled by script: element.animate().
  • Motion based on live input or calculations: a requestAnimationFrame loop driven by elapsed time.

Whatever you choose, animate transform and opacity where possible and keep the loop's work small.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course