Timing Strategies

If you've programmed animations in JavaScript before, you may have used either setInterval or setTimeout to get your drawing function to be called.

The problem with using these two approaches for drawing is that they have no relation to the browser's render cycle. That is, they aren't synced to when the browser is going to draw a new frame, which can leave the animation out of sync with the user's machine. For example, if you use setInterval or setTimeout and assume 60 frames a second, and the user's machine is actually running a different frame rate, you'll be out of sync with their machine.

Even though requestAnimationFrame is available on all WebGL-enabled browsers, we'll leverage our own animation JavaScript timers for educational purposes. In production, it is recommended that you leverage the browser's optimized version.

In this section, we will create a JavaScript timer that will allow us to control the animation. As we mentioned previously, we will implement a JavaScript timing strategy that provides independence between how fast your computer can render frames and how fast you want the animation to go. We will refer to this property as the animation rate.

Before moving forward, we must address a caveat about working with timers: JavaScript is not a multithreaded language. This means that if there are several asynchronous events occurring at the same time (blocking events), the browser will queue them for posterior execution. Each browser has a different mechanism to deal with blocking event queues.

There are two blocking event-handling alternatives for the purpose of developing an animation timer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.22.135