Adding an Animation Loop
Add an animation loop and use requestAnimationFrame function for smooth and efficient rendering.
Limitations with scene animation
At this point, the scene is very static. We can’t move the camera around and nothing is moving. If we want to animate the scene, the first thing that we need to do is find some way to re-render the scene at a specific interval. Before HTML5 and the related JavaScript APIs came along, the way to do this was by using the setInterval(function,interval)
function. With setInterval
, we could specify a function that, for instance, would be called every 100 milliseconds. The problem with this function is that it doesn’t take into account what is happening in the browser. If we were browsing another tab, this function would still be fired every couple of milliseconds. Besides that, setInterval
isn’t synchronized when the screen is redrawn. This can lead to higher CPU usage, flickering, and generally poor performance.
Luckily, modern browsers have a solution for that with the requestAnimationFrame
function.