Skip to content

Instantly share code, notes, and snippets.

@entomb
Created July 3, 2014 12:46
Show Gist options
  • Save entomb/b675f949048c5750a297 to your computer and use it in GitHub Desktop.
Save entomb/b675f949048c5750a297 to your computer and use it in GitHub Desktop.
A small tool to pump numbers up (or down)
/**
* numberPump
* small tool to pump it up
* @author Joanthan Tavares
* @class numberPump
* @class numberPump
* @param options {object} pump this up
* @param options.from {Number} pump this up
* @param options.to {Number} untill it gets here
* @param options.element {DOMelement} if passed, the step will pe set on the .innerHTML or .value of this object
* @param options.speed {Number} default=10 the ms interval to run the updater
* @param options.onStart {Function} callback before it starts to pump
* @param options.onStep {Function} callback on each step of the way
* @param options.onEnd {Function} callback after its pumped
*
*/
var numberPump = function(options){
var o = options || {}
this.from = parseInt(o.from) || 0;
this.to = parseInt(o.to) || 0;
if('onStart' in o){
o.onStart.call(this);
}
var f = {
linear: function (t) { return t },
easeInQuad: function (t) { return t*t },
easeOutQuad: function (t) { return t*(2-t) },
easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t },
easeInCubic: function (t) { return t*t*t },
easeOutCubic: function (t) { return (--t)*t*t+1 },
easeInOutCubic: function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 },
easeInQuart: function (t) { return t*t*t*t },
easeOutQuart: function (t) { return 1-(--t)*t*t*t },
easeInOutQuart: function (t) { return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t },
easeInQuint: function (t) { return t*t*t*t*t },
easeOutQuint: function (t) { return 1+(--t)*t*t*t*t },
easeInOutQuint: function (t) { return t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t }
}
var easing = f.easeInQuad;
var speed = o.speed || 10;
var goingUp = !!(this.to>this.from);
var goingDown = !goingUp;
var t = 6;
this.current = this.from;
var stepFunction = function(np){
if(goingUp){
np.current+=easing(t++);
if(np.current>=np.to){
np.current = np.to;
}
}else if(goingDown){
np.current-=easing(t++);
if(np.current<=np.to){
np.current = np.to;
}
}else{ //equal?
clearTimeout(pumpTimeout);
return;
}
if('element' in o && 'value' in o.element){
o.element.value = np.current;
}else if('element' in o && 'innerHTML' in o.element){
o.element.innerHTML = np.current;
}
if('onStep' in o){
o.onStep.call(np,np.current);
}
if((goingUp && np.current>=np.to)
|| (goingDown && np.current<=np.to)){
clearTimeout(pumpTimeout);
if('onEnd' in o){
o.onEnd.call(np,np.current);
}
}
}
var pumpTimeout = setInterval(stepFunction,speed, this);
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment