Home > Blockchain >  Formatting a setInterval() Timer with thousands separators
Formatting a setInterval() Timer with thousands separators

Time:05-25

Newbie here, and I've been playing around with this setInterval() count up timer, and my goal here is to get the counter to display thousands (,) separators while counting up. Is there an easy way to do this, or would it require a difficult solution? I've tried to play around with toLocaleString, but to no avail. Here's my code so far.

<p id="test">0</p>
<button id="button" onclick="b().toLocaleString('en-US')">Start</button>
<script>
    var c = 0;
    function a() { 
        document.getElementById("test").innerHTML =   c;
    }
function b() {
setInterval(a, 5);
}
</script>

CodePudding user response:

Put everything in a(). Let c increment as a number first then format it into a string with.toLocalString() then assign the string to the DOM. In the example <p> has been changed to a <output> and the string is assigned to it's .value property. b() is just a wrapper that starts an interval, it doesn't return a value so b().toLocalString() does nothing but set off an error.

<output id="test">0</output><br>
<button onclick="b()">Start</button>
<script>
  const test = document.getElementById("test");
  let c = 0;

  function a() {
      c;
    let formatted = c.toLocaleString('en-US');
    test.value = formatted;
  }

  function b() {
    setInterval(a, 5);
  }
</script>

CodePudding user response:

The problem in your code is that you called .toLocaleString('en-US') to b(), but b() is not returning anything, hence nothing is proccesed by .toLocaleString('en-US').

The right way is to cast .toLocaleString('en-US') to a string (e.g. c) then print it to document.getElementById("test").

var c = 0;
function a() {
    c;
  document.getElementById("test").innerHTML = c.toLocaleString('en-US');
}
function b() {
  setInterval(a, 5);
}
<p id="test">0</p>
<button id="button" onclick="b()">Start</button>

  • Related