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