Bouncing Balls - Unoptimized Version

The goal here isn't necessarily to fix the animation. Your first goal is to profile the unoptimized version and understand how to:

In this exercise, we have an animation of multiple balls bouncing within a container. Initially, the animation is slow and janky because it repeatedly reads and writes layout properties like offsetLeft, offsetTop, style.left, and style.top inside a loop. This causes frequent layout recalculations, known as layout thrashing, which burdens the browser's main thread and degrades performance.

When the "Optimize" button is clicked, the animation is refactored to store positions in JavaScript variables and update the ball positions using CSS transform: translate(), instead of left and top. This approach avoids triggering layout recalculations because transforms are handled by the GPU, leading to smoother animations. Additionally, the code switches to using requestAnimationFrame(), which synchronizes animation updates with the browser's rendering cycle for better efficiency.

The key takeaway is that frequent DOM reads and writes can negatively impact performance. By minimizing layout-dependent operations and leveraging CSS transforms and requestAnimationFrame(), we create efficient, high-performance animations. For more details, you can refer to MDN's guides on High Performance Animations and Optimizing JavaScript animations.

Finished?

Head back to the CPU Lesson