Simulates the Adobe Flash timeline. You define the amount of frames, the speed in fps (frames per second) and, at each frame passage an event is called, useful for animations.
[UPDATED CODE AND HELP CAN BE FOUND HERE]
1
2 //+ Jonas Raoni Soares Silva
3 //@ http://jsfromhell.com/classes/timeline [v1.0]
4
5 TimeLine = function(fps, f){
6 this.fps = fps, this.frames = f;
7 };
8 with({o: TimeLine, $: TimeLine.prototype}){
9 o.timers = [];
10 $.running = !!($.current = +(o.timer = $.time = null));
11 o.run = function(){
12 var o = this;
13 o.timer || (o.timer = setInterval(function(){
14 for(var h, d = +(new Date), t = o.timers, i = t.length; i--;){
15 (!t[i].running || ((d - t[i].time) / (1e3 / t[i].fps) > t[i].current + 1 &&
16 t[i].onframe(++t[i].current), t[i].current >= t[i].frames)) &&
17 (h = t.splice(i, 1)[0], h.stop(1));
18 }
19 }, 1));
20 };
21 $.start = function(c){
22 var o = this, t = TimeLine;
23 if(o.running) return;
24 o.running = true, o.current = c || 0;
25 o.time = new Date, o.onstart && o.onstart();
26 if(!o.onframe || o.frames <= 0 || o.fps <= 0)
27 return o.stop(1);
28 t.timers.push(this), t.run();
29 };
30 $.stop = function(){
31 var o = this;
32 o.running = false;
33 if(!TimeLine.timers.length)
34 TimeLine.timer = clearInterval(TimeLine.timer), null;
35 arguments.length && o.onstop && o.onstop();
36 };
37 }
Example
1
2
3 <div id="box" style="position: absolute; top: 100px; background: #efe; width: 100px; height: 100px">25 fps</div>
4 <div id="box2" style="position: absolute; top: 300px; background: #ff9; width: 100px; height: 100px">12 fps</div>
5
6 <strong>TimeLine working together with the ease in quad function.</strong><br />
7
8 <script type="text/javascript">
9 Math.ease = function (t, b, c, d) {
10 if ((t /= d / 2) < 1)
11 return c / 2 * t * t + b;
12 return -c / 2 * (--t * (t - 2) - 1) + b;
13 };
14
15 var o = new TimeLine(25, 50), d = document, b = d.getElementById("box");
16 o.onframe = function(){
17 b.style.left = Math.ease(this.current, 0, 400, 30) + "px";
18 };
19 o.onstart = function(){
20 d.body.appendChild(d.createTextNode("Started"));
21 };
22 o.onstop = function(){
23 d.body.appendChild(d.createTextNode(" - Finished (" + (((new Date) - this.time)) + " msec)"))
24 d.body.appendChild(d.createElement("br"));
25 this.start();
26 };
27 o.start();
28
29
30 var o2 = new TimeLine(12, 50), b2 = d.getElementById("box2");
31 o2.onframe = function(){
32 b2.style.left = Math.ease(this.current, 0, 400, 30) + "px";
33 };
34 o2.onstop = function(){
35 this.start();
36 };
37 o2.start();
38 </script>