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>
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>