JS counter continuously updating

user1600005 picture user1600005 · Aug 15, 2012 · Viewed 8.2k times · Source

How to implement a live and persistent number counter on a site

So I was looking at this question (^) and I want to do the exact same thing except a little different.

I need one of these that counts up 15.8 cents per second from the numb $138,276,343

Preferably I would like to have the commas like a normal dollar amount.

Any way I could get this working? I'm stumped. Like the poster of the above question, I don't have much JS knowledge.

Answer

Evan Kennedy picture Evan Kennedy · Aug 15, 2012

This took me quite a long time to answer since I had to create my own format currency function.

A live demo can be found here: http://jsfiddle.net/dm6LL/

The basic updating each second is very easy and will be done through JavaScript's setInterval command.

setInterval(function(){
    current += .158;
    update();
},1000);

The update() function you see in the above code is just a simple updater referencing an object with the amount id to put the formatted current amount into a div on the page.

function update() {
    amount.innerText = formatMoney(current);
}

Amount and current that you see in the update() function are predefined:

var amount = document.getElementById('amount');
var current = 138276343;

Then all that's left is my formatMoney() function which takes a number and converts it into a currency string.

function formatMoney(amount) {
    var dollars = Math.floor(amount).toString().split('');
    var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1];
    if(typeof cents == 'undefined'){
        cents = '00';
    }else if(cents.length == 1){
        cents = cents + '0';
    }
    var str = '';
    for(i=dollars.length-1; i>=0; i--){
        str += dollars.splice(0,1);
        if(i%3 == 0 && i != 0) str += ',';
    }
    return '$' + str + '.' + cents;
}​