-2

Really sorry if you've gone over this already with me. The good news: I've made progress. The bad news: it's broken progress.

I have a function that counts up from a certain number. It's a big number, and I need to insert commas in the correct places. Here's the code I've put together. It works at first, but then displays NaN...

http://jsfiddle.net/blackessej/TT8BH/7/

function createCounter(elementId,start,end,totalTime,callback)
{
    var jTarget=jQuery("#"+elementId);
    var interval=totalTime/(end-start);
    var intervalId;
    var current=addCommas(start)+'';
    var f=function(){
        jTarget.text(current);
        if(current==end)
        {
            clearInterval(intervalId);
            if(callback)
            {
                callback();
            }
        }
        ++current;
    }
    intervalId=setInterval(f,interval);
    f();
}
jQuery(document).ready(function(){
    createCounter("counter",12714086,9999999999,10000000000000,function(){
        alert("finished")
    })
})

function addCommas(str) {
    var amount = new String(str);
    amount = amount.split("").reverse();

    var output = "";
    for ( var i = 0; i <= amount.length-1; i++ ){
        output = amount[i] + output;
        if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
    }
    return output;
}
blackessej
  • 706
  • 1
  • 17
  • 35
  • possible duplicate of [Number counting up needs commas, decimal point](http://stackoverflow.com/questions/7124793/number-counting-up-needs-commas-decimal-point) – jfriend00 Aug 19 '11 at 21:48

2 Answers2

0

When you call addCommas, you are returning a String, nicely formatted for humans, but terrible for things like ++. You need to track and modify the start variable, and only convert to string when necessary:

var f=function(){
    jTarget.text(addCommas(start));
    if(start==end)
    {
        clearInterval(intervalId);
        if(callback)
        {
            callback();
        }
    }
    ++start;
}
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
0

The problem comes from adding the commas to the number. Just convert the number to the comma string before putting it in the .text() function:

http://jsfiddle.net/TT8BH/11/

Dennis
  • 32,200
  • 11
  • 64
  • 79