Categories
interview

Smooth Animation

The following is a method to perform smooth animation of an element from left to right given the duration and distance. 60 frames per second (fps) is the approximate frame rate for this . In this example, the element is being animated from left to right at 60 fps for a duration of 2 seconds (2000 ms) and a distance of 100px.

Javascript (ES6)

const animate = (element, duration/*seconds*/, distance) => {
  let start;
  const durationMs = duration * 1000;
  const speed = distance / durationMs;
  const step = (timestamp) => {
    if (start === undefined)
      start = timestamp;
    const elapsed = timestamp - start; // milliseconds
    element.style.transform = 'translateX(' + Math.min(speed * elapsed, distance) + 'px)';
    if (elapsed < durationMs) { // Stop the animation after duration
      window.requestAnimationFrame(step);
    }
  }
  window.requestAnimationFrame(step);
}
animate(document.getElementById('child'), 1, 100);

HTML

<div id="parent">
  <div id="child">
  </div>
</div>

CSS

#parent {
  height: 200px;
  width: 200px;
  background-color: lightblue;
}
#child {
  height: 100px;
  width: 100px;
  background-color: lightgreen;
}

DEMO