WEBINAR: On-demand Event
Replace Oracle with the NoSQL Engagement Database: Why and how leading companies are making the switch REGISTER >
In this tutorial we'll start out with the basics of animation, how to make things move, turn animations on and off, and determine the edges of the space where you want the motion to take place. All of the code in this tutorial has been tested on Mozilla Firefox, Windows, Linux, Konquerer on Linux and MS IE on Windows.
A Matter of Timing
At some point most of us have played with a flip book to see how animation works. The classic flip book is a little ball that bounces around the field of the page as the pages flip past. The image isn't really moving, but each page has the image placed slightly differently from the last, and our brains perceive that as movement. In TV and movies, the same thing happens, only without all the pages sitting in our hands. The images flip past our vision, one at a time, at a rate of 24, 25 or 30 images per second, depending on the medium we are viewing (film, PAL video and NTSC video respectively). This is known as the "frame rate."
On the Internet, we often cheat a bit, seeing exactly how far we can push the weaknesses in human perception to use smaller files and less computer power to present the same experience to the end user. It just so happens that for most Web animations you can get away with exactly half the optimal frame rate without the movement looking too choppy. So, for this tutorial we'll use 1 frame every 80 milliseconds.
In the case of setTimeout(), if you want to run a single function over and over at the time count that you have set, you need to put the function inside of the function it calls. So you will end up with a function that looks something like:
In the case of setInterval(), the call should be made outside the function that you want to repeat. Otherwise, you end up with multiple instances of your interval, a strange acceleration of movement, and a big, fat memory leak.
Chances are, at some point you'll want to stop the animation. To do so, you'll need either clearTimeout() or clearInterval(). Both of these clearing functions take a variable which represents a timing object, and clears it's timer. To make these work, you need to create the object that your clear function will stop.Timeout example: