JavaScript already has a device more suitable for animation and really used for animation. Before I start to explain it, look at my code sample with a pretty simple example of animation, the one which comes with my recent April 1st article
Some Programming Approaches to "Neuro-Linguistic Programming".
In the code, you will see the
fallback to analogous functions of particular browsers to the last resort of
window.setTimeout
, in cases when this function is not included in particular JavaScript implementation (not very likely, only for obsolete browsers).
Here is the idea
function showException(exception) {
alert( exception.name + ":\n" + exception.message +
"\n" + "\nLine: " + exception.lineNumber +
"; column: " + (exception.columnNumber + 1) +
"\n\n" + exception.stack);
}
try { (function() {
if (!window.requestAnimationFrame)
window.requestAnimationFrame =
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element) { window.setTimeout(callback, 1000 / 60); }
doSomeInitialization();
var after, before = now();
function frame() {
after = now();
RenderFrame(Math.min(1, (after - before) / 1000.0));
before = after;
requestAnimationFrame(frame);
}
frame();
})(); } catch(e) { showException(e); }
var duration = 0;
var renderFrame(timeStamp) {
duration += dTime;
if (duration <= settings.delay) return;
duration -= settings.delay;
}
Please see:
https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame.
Main function is anonymous, using the IIFE JavaScript
design pattern. Please see:
http://en.wikipedia.org/wiki/Immediately-invoked_function_expression.
My demo works with HTML5
<canvas>
element, but I believe you can use any other kind of animation, based on any properties of any HTML elements.
You can combine animated behavior with interactive, based on user input events (keyboard, mouse). One my example is more complicated animated application:
Tetris on Canvas. Sorry if it's a bit too complex for understanding (I just don't know any simpler example), but perhaps you will be able to catch and idea from my explanations above and the article.
—SA