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. In this example, the element is being animated from left to right at 60 fps for a duration of 5 seconds and a distance of 100px. The animation is cancelled midway at 3 seconds using cancelAnimationFrame().

Javascript

const animate = (element, duration/*seconds*/, distance) => {
  if (!element) {
    return;
  }
  element.style.position = 'relative';
  let start;
  let requestID;
  const durationMs = duration * 1000; // Milliseconds.
  const step = (timestamp) => {
    if (start === undefined)
      start = timestamp;
    const elapsed = timestamp - start;
    const fraction = Math.min(elapsed / durationMs, 1);
    element.style.transform = `translateX(${fraction * distance}px)`;
    if (elapsed < durationMs) { // Stop the animation after duration.
      requestID = requestAnimationFrame(step);
    }
  }
  requestID = requestAnimationFrame(step);
  return () => {
    element.style.transform = 'translateX(0px)';
    cancelAnimationFrame(requestID);
  };
}

const cancel = animate(document.getElementById('child'), 5, 100);

setTimeout(() => {
  cancel();
}, 3000);

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

This can be further optimized using the FLIP technique