Skip to content

Instantly share code, notes, and snippets.

@duzun
Created November 12, 2014 09:11
Show Gist options
  • Save duzun/d7b99687aff81f878739 to your computer and use it in GitHub Desktop.
Save duzun/d7b99687aff81f878739 to your computer and use it in GitHub Desktop.
Nice count to number
/// Nice count to number (by DUzun)
;(function (global, FUNCTION, Number) {
var $ = global.jQuery || global.Zepto;
$.fn.counto = function fcounto(nr,dl,done) {
if(!dl) dl = 400;
var start = $.now(),
end = start + dl,
delay = 10,
rwm = parseFloat,
rwc,
fx = S(nr).split('.');
if(typeof xNumber === FUNCTION) {
rwm = xNumber;
rwc = xNumber;
}
fx = fx.length > 1 ? fx[1].length : 0;
nr = rwm(nr);
this.each(function (i, e) {
var $this = $(e),
data = $this.data(),
mh = $this.is(':input') ? 'val' : 'text',
v = $this[mh](),
val = rwc ? new rwc(v) : rwm(v),
ofs = Number(val),
last = ofs,
inter = ofs - nr,
sv = function sv() {
if(data._cto) clearTimeout(data._cto);
var now = $.now(), v;
if(now < end && last != nr) {
v = (ofs - (now-start) / dl * inter).toFixed(fx);
data._cto = setTimeout(sv, delay);
} else {
v = fx ? nr.toFixed(fx) : nr;
delete data._cto;
}
if(v != last) {
last = v;
rwc ? (val.value = v) : (val = v);
$this[mh](val);
}
if(!data._cto) {
if(typeof done === FUNCTION) done.call(e, nr, val);
}
} ;
sv();
});
} ;
})(this, 'function', Number);
@duzun
Copy link
Author

duzun commented Feb 7, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment