Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - JS counter continuously updating

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...