JS counter continuously updating
Asked Answered
B

1

5

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.

Brien answered 15/8, 2012 at 7:30 Comment(0)
L
11

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;
}​
Latium answered 15/8, 2012 at 8:28 Comment(6)
That is awesome!!!! One question though, is there a way to make it update continuously rather than onload? I need the number to always go up and not refresh from the start every time the page is refreshed. Either way though the code is awesome!!! Thanks so much!!!Brien
You could still do it onload, but just calculate what the starting number should be given the current date. I assume the number $138,276,343 is based on a particular time and date?Separatist
Correct, that number was calculated on July 21st, 2012 and it has gone up the .158 per second since thenBrien
Cool - I've modified Evan's demo slightly to accommodate this: jsfiddle.net/dm6LL/3Separatist
I've modified mine more as well. Mine starts at August 15th and goes up .158 for every second after that. You can edit the starting date very easily as well. Here is the demo: jsfiddle.net/dm6LL/5Latium
For some reason the function didn't work if i didn't add var i at the beginning of the loop, i guess strict mode is on: for(var i=dollars.length-1; i>=0; i--)Pietje

© 2022 - 2024 — McMap. All rights reserved.