Skip to content

Instantly share code, notes, and snippets.

@os0x
Created September 18, 2009 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save os0x/188922 to your computer and use it in GitHub Desktop.
Save os0x/188922 to your computer and use it in GitHub Desktop.
// Tweener Like snippet
function Tween3(item, opt) {
var TIME = 10, TM_EXP = /(\+)?\$([\#\d])/g, actions = [],
easing = function(t, b, c, d){return c*t/d + b;},
T = {time:1,onComplete:1,transition:1,delay:1};
var sets = [], delay = opt.delay*1000 || 0, start = new Date()*1 + delay, time = (opt.time||1) * 1000;
for (var k in opt) if (!T[k]) {
var set = opt[k], from = set.from || parseFloat(item[k]) || 0, tmpl = set.tmpl || '-$#';
sets.push({key:k, from:from, to:set.to, tmpl:tmpl});
}
var act = {item:item,sets:sets,time:time,start:start,delay:delay,easing:opt.transition || easing};
if (opt.onComplete) act.onComplete = opt.onComplete;
actions.push(act);
if (actions.length === 1) loop();
function loop(){
var now = new Date()*1;
for (var i = actions.length; i--;) {
var act = actions[i], duration = now - act.start;
if (duration < 0) continue;
for (var j = 0, L = act.sets.length; j < L; ++j) {
var set = act.sets[j], val = act.easing(duration, set.from, set.to - set.from, act.time);
act.item[set.key] = set.tmpl.replace(TM_EXP,
function(m, p, m1){return p && val < 0 ? 0 : (m1 == '#' ? val : val.toFixed(m1));});
}
if (duration > act.time) {
for (var j = 0; j < L; ++j) {item[sets[j].key] = sets[j].tmpl.replace(TM_EXP, sets[j].to);}
if (typeof act.onComplete == 'function') act.onComplete(item);
actions.splice(i, 1);
}
}
if (actions.length) setTimeout(loop, TIME);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment