Skip to content

Instantly share code, notes, and snippets.

@danwaz
Last active December 20, 2015 00:29
Show Gist options
  • Save danwaz/6042163 to your computer and use it in GitHub Desktop.
Save danwaz/6042163 to your computer and use it in GitHub Desktop.
Counting Animation
var counterAnimation = function($num, to, from){
var totalTime = 250,
direction = to - from,
counter = 0,
interval = 6,
iterator = (Math.abs(to-from)) / (Math.round(totalTime/interval));
var _endCount = function(){
clearInterval(counterInterval);
$num.html(Math.round(to));
}
var counterInterval = window.setInterval(function(){
//stop counter
if(counter >= totalTime){ _endCount(); return 0; }
if(direction < 0){
//count down
from -= iterator;
if(from <= to){ _endCount(); return 0;}
} else {
//count up
from += iterator;
if(from >= to){ _endCount(); return 0;}
}
$num.html(Math.round(from));
counter += interval;
}, interval);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment