This code updates numbers. However, it runs again and again on every scroll. I would like the numbers to be updated only once when I see them on the viewport. Then, the function can run again if I scroll past the viewport and reach the numbers again.
Here is my code:
class Counter {
constructor(id, target, speed, appendString) {
this.id = id;
this.target = target;
this.speed = speed;
this.appendString = appendString;
}
start() {
const container = document.querySelector(this.id);
container.innerText = 0;
let count = 0;
function updateCount(counter, target, speed, appendString) {
if (count < target) {
counter.innerText = `${count} ${appendString}`;
count++;
setTimeout(
() => updateCount(counter, target, speed, appendString),
speed
);
} else {
counter.innerText = `${target} ${appendString}`;
}
}
updateCount(container, this.target, this.speed, this.appendString);
}
}
const counter1 = new Counter('#headline-e6423da8', 156, 15, '');
const counter2 = new Counter('#headline-77ad9299', 227, 15, '');
const counter3 = new Counter('#headline-8255ec52', 91, 15, '%');
const counter4 = new Counter('#headline-5e08a0cb', 30, 15, '+');
window.addEventListener('scroll', () => {
counter1.start();
counter2.start();
counter3.start();
counter4.start();
});