The oldschool & Classic way of animating content in using SetTimeout()
or setInterval()
.
But those function can heavily decrease performance. Browser wants to repaint screen in approximately 60FPS (or 16.6ms). But it’s not possible when the stack is not empty. Every call to mentioned functions put a task onto a queue, which is moved to a stack after a specified time. So it might happen that if you abuse them You may block UI. Play with it by adding junk to stack - in this case, a lot of factorial recursive calls.
See the Pen setInterval() by Karol Świeca (@khazarr) on CodePen.
Another example uses requestAnimationFrame
for drawing. It’s a simple solution with recursive calls
Some theory at the beginning
requestAnimationFrame()
performane.now()
requestAnimationFrame(console.log)
will print value of performance.now()
cancelAnimationFrame()
Ok, let’s see it in action, the same scenario. Play with it and compare your performance when the stack is heavily loaded with factorial recursive calls
See the Pen requestAnimationFrame - drawing by Karol Świeca (@khazarr) on CodePen.
PS. It might happen that your machine is cutting edge piece fo tech, and you’ll need to add some more recursive calls to see some UI blocking
PS2. actually, browsers may throw Uncaught RangeError: Maximum call stack size exceeded
so you won’t see this effect of UI blocking, so just enjoy animation ;)