requestAnimationFrame
is a built-in browser API designed specifically for animations. It tells the browser to call a function and redraw the canvas just before the next screen refresh. This makes animations smoother and more efficient compared to methods like setInterval
or setTimeout
.
Inside the drawBox
function, we call requestAnimationFrame(drawBox)
to schedule the next frame. This makes sure that the animation continues to run and without this call, the animation would only execute once.
To stop the animation, a condition checks whether the rectangle's right edge has reached the canvas width. If this condition is met, requestAnimationFrame
is not called again, and the animation stops.