0

This is my code to render an auto increment counter on my page:

<script>
  document.addEventListener("DOMContentLoaded", function(event) {
    var START_DATE_1 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
    var INTERVAL_1 = 3; // in seconds
    var INCREMENT_1 = 1; // increase per tick
    var START_VALUE_1 = 0; // initial value when it's the start date
    var count_1 = 0;

    var msInterval_1 = INTERVAL_1 * 1000;
    var now_1 = new Date();
    count_1 = parseInt((now_1 - START_DATE_1)/msInterval_1) * INCREMENT_1 + START_VALUE_1;
    document.getElementById('counter_1').innerHTML = count_1;
    setInterval(function() {
      count_1 += INCREMENT_1;
      document.getElementById('counter_1').innerHTML = count_1;
    }, msInterval_1);
  });
</script>

I would like to render the numbers of the counter with thousand separator (example: 2.000.000)

How should I edit the script?

Thanks in advance.

Francesco
  • 387
  • 5
  • 17
  • `count_1.toLocaleString()` works in most browsers – dandavis Sep 14 '16 at 19:04
  • 2
    Possible duplicate of [How to print a number with commas as thousands separators in JavaScript](http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – PM 77-1 Sep 14 '16 at 19:05

1 Answers1

1

On modern browsers you can use the Intl API

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The constructors for Collator, NumberFormat, and DateTimeFormat objects are properties of the Intl object. This page documents these properties as well as functionality common to the internationalization constructors and other language sensitive functions.

I'm using Italian in the following example, just based on your name and it uses your required format.

var START_DATE_1 = new Date('July 18, 2016 10:30:00').getTime(); // put in the starting date here
var INTERVAL_1 = 3; // in seconds
var INCREMENT_1 = 1; // increase per tick
var START_VALUE_1 = 0; // initial value when it's the start date
var msInterval_1 = INTERVAL_1 * 1000;
var now_1 = Date.now();
var count_1 = Math.trunc((now_1 - START_DATE_1) / msInterval_1) * INCREMENT_1 + START_VALUE_1;

function formatNumber(number) {
  return new Intl.NumberFormat('it').format(number);
}

document.getElementById('counter_1').textContent = formatNumber(count_1);
setInterval(function() {
  count_1 += INCREMENT_1;
  document.getElementById('counter_1').textContent = formatNumber(count_1);
}, msInterval_1);
<pre id="counter_1"></pre>
Xotic750
  • 22,914
  • 8
  • 57
  • 79