When should I clear the interval to save some processor cycles?
Itβs better not to use the interval at all for several reasons:
- Intervals cannot be synchronized to track the VBLANK gap, so from time to time you will be jerky.
- If you use setInterval, you run the risk of stacking calls (in this case, not a high risk).
And itβs much better, as you already know, to use requestAnimationFrame . This is a less processor hunger, able to synchronize and control fewer resources in general, even if the current tab / window is not active.
Why does animation slow down in the third lap?
Your drawing calls accumulate, which slows everything down ( setInterval not cleared).
Here is a different approach to this. This is a simplified method and uses differential coloring.
ONLINE DEMO
The main draw function here takes two arguments, the index of the circle and the current angle for this circle. The radius of the circles is stored in the array:
..., sa = 0, // start angle ea = 359, // end angle angle = sa, // current angle oldAngle = sa, // old angle steps = 2, // number of degrees per step current = 0, // current circle index circles = [70, 80, 90], // the circle radius numOfCircles = circles.length, ...
The function saves the old angle and only draws a new segment between the old angle and the new angle with 0.5 added to compensate for failures due to smoothing, rounding errors, etc.
function drawCircle(circle, angle) { angle *= deg2rad;
The cycle increases the angle; if it is higher than or equal to the final angle, it will reset the angle and increase the counter of the current circle. When the current counter reaches the last lap, the loop ends:
function loop() { angle += steps;