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()

  • parameter
    • a callback function that will be called at the next repaint
    • callback first parameter has a value of performane.now()
    • i.e requestAnimationFrame(console.log) will print value of performance.now()
  • return
    • an integer id value which you can use to 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 ;)


Karol Świeca

My thougths on JavaScript, AWS Cloud and other aspects of being Software Engineer