Search code examples
javascriptparseint

Adding comma to setinterval counter value


the title might not be the right one, sorry about that.

I'm trying to make a livecounter for a website, the idea it's to show a fake number increasing every second. I've this so far

var START_DATE = new Date("November 27, 2014 13:30"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 901; // initial value when it's the start date
var count = 0; //finally this shit is working

window.onload = function()
{
 var msInterval = INTERVAL * 1000;
 var now = new Date();
 count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
 document.getElementById('counter').innerHTML = count;
 setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = count;", msInterval);
}
   
<div id="counter"></div>

Which is shows a number like "24350919" increasing each second, I want to convert it to 24,350,919. I tried with parseFloat, but I couldn't make it work.

Can someone give me a hand with this? thank you!


Solution

  • EDIT:-

    var START_DATE = new Date("November 27, 2014 13:30"); // put in the starting date here
    var INTERVAL = 1; // in seconds
    var INCREMENT = 2; // increase per tick
    var START_VALUE = 901; // initial value when it's the start date
    var count = 0; //finally this shit is working
    
    
    window.onload = function() {
      var msInterval = INTERVAL * 1000;
        var now = new Date();
        count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
        document.getElementById('counter').innerHTML = addCommas(count);
        setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = addCommas(count);", msInterval);
    }
    
    function addCommas(myStr)
    {
        myStr += '';
        var x = myStr.split('.');
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }
    <div id="counter"></div>


    You can try to use toLocaleString() like this:

    var n = 24350919
    n.toLocaleString()
    

    In your case it would be like

    setInterval("count += INCREMENT; document.getElementById('counter').innerHTML =
             count;", msInterval.toLocaleString());