I've written a function to update the contents of an HTML element to display a counter. On pageload the counter will recieve an initial value, every five minutes the new value will be requested from the server. Over the next five minutes, the initial value will loop to the new value.
const increment = function(counter, newValue, timespan = 300000) {
const currentValue = Number(counter.textContent);
const diff = newValue - currentValue;
const interval = timespan / diff;
const intervalFn = setInterval(function() {
counter.textContent++;
if (counter.textContent == newValue) clearInterval(intervalFn);
}, interval);
};
For simplicity I've left the server calls out:
<h1>0</h1> //html
const counter = document.querySelector("h1");
counter.textContent = 50;
increment(counter, 100);
1 Answer 1
This looks a bit strange:
counter.textContent++;
Incrementing text... waaat? If you check the type of the .textContent
property using typeof
, it will tell you that it's a string
.
For every increment, JavaScript has to convert the string to a number, performs the increment, and converts it back.
It would be cleaner to use a local variable to perform the increments,
and update counter.textContent
from the updated value of that variable.
For example you already have the currentValue
local variable, you could change that from const
to var
, and use that for counting.